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

扩展程序中的 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

参考文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值