Chrome 56 扩展开发实验03:跨域 XMLHttpRequest 请求

来源:互联网 发布:windows安装jdk 编辑:程序博客网 时间:2024/06/15 01:23

扩展程序中的 XMLHttpRequest 对象不受同源策略的限制。

文件列表

+ chrome56-extension-xmlhttprequest      icon.png      manifest.json      content.js

manifest.json

内容如下:

{  "name": "testXMLHttpRequest",  "version": "1.0",  "manifest_version": 2,  "description": "XMLHttpRequest 测试",  "icons":  {    "48": "icon.png"  },  "browser_action":  {    "default_icon": "icon.png"  },  "content_scripts": [    {      "matches": ["http://*/*", "https://*/*"],      "js": ["content.js"]    }  ]}

content.js

function sendXMLHttpRequest(url, callback){  var xhr = new XMLHttpRequest();  xhr.onreadystatechange = function (data)  {    if (xhr.readyState == 4)    {      if (xhr.status == 200)      {        var data = JSON.parse(xhr.responseText);        callback(data);      }      else      {        callback(null);      }    }  }  xhr.open('GET', url, true);  xhr.send();};function onText(data){  if (data)  {    alert('跨域请求的结果:' + data.name + ' ' + data.version);  }  else  {    alert('跨域请求的结果失败');  }};//sendXMLHttpRequest('http://localhost:8080/api/version', onText);sendXMLHttpRequest('https://localhost:8443/api/version', onText); // 访问自定义的服务

执行效果

每当有页面被打开或者被刷新,会弹出消息框,显示返回的结果,或者失败。

注意事项

  1. 如果浏览器请求的是HTTPS协议的网址,而插件中请求的HTTP协议的地址,将返回类似下面的错误:

Mixed Content: The page at ‘https://www.xxx.net/sssss’ was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint ‘http://localhost:8080/api/version‘. This request has been blocked; the content must be served over HTTPS.

  1. 如果自己构建HTTPS服务,需要将证书导入到浏览器中,否则可能返回不了数据。

实验环境:

  • Windows 7 Profressional (64位)
  • Chrome 56.0.2924.87

参考文档

  • http://open.chrome.360.cn/extension_dev/xhr.html
0 0
原创粉丝点击