tips:允许跨域示例
{
...
"permissions": [
"*://*.wikipedia.org/*"
]
}
-
每次发起请求,只要调用httpRequest函数,并传入要请求的URL和接收返回结果的函数就可以了。
为什么要使用callback函数接收请求结果,而不直接用return将结果作为函数值返回呢?
因为XMLHttpRequest不会阻塞下面代码的运行。(异步)
function httpRequest(url, callback){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
}
xhr.send();
}
- 小项目 用户IP展示
manifest
{
"manifest_version": 2,
"name": "查看我的IP",
"version": "1.0",
"description": "查看我的电脑当前的公网IP",
"icons": {
"16": "images/icon16.png",
"48": "images/icon48.png",
"128": "images/icon128.png"
},
"browser_action": {
"default_icon": {
"19": "images/icon19.png",
"38": "images/icon38.png"
},
"default_title": "查看我的IP",
"default_popup": "popup.html"
},
"permissions": [
"http://user.ip138.com/ip/"
]
}
popu.html
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
}
body {
width: 400px;
height: 100px;
}
div {
line-height: 100px;
font-size: 42px;
text-align: center;
}
</style>
</head>
<body>
<div id="ip_div">正在查询……</div>
<script src="js/my_ip.js"></script>
</body>
</html>
my_ip.js
function httpRequest(url, callback){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
}
xhr.send();
}
httpRequest('http://user.ip138.com/ip/', function(ip){
document.getElementById('ip_div').innerText = ip;
});