chrome 扩展中的跨域 XMLHttpRequest [英] Cross-Origin XMLHttpRequest in chrome extensions

查看:41
本文介绍了chrome 扩展中的跨域 XMLHttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 chrome 扩展 API 跨域调用使用 XMLHttpRequest 对象,如果设置了权限:

According to chrome extensions API cross-origin calls using XMLHttpRequest object should be allowed if permissions are set:

扩展可以与其源之外的远程服务器通信,只要它首先请求跨源权限即可.

An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.

我正在密切关注教程,但下面的代码给了我一个错误信息:

I am closely following the tutorial but the code below is giving me an error message:

XMLHttpRequest 无法加载 http://www.google.com/search?hl=en&q=ajax.Access-Control-Allow-Origin 不允许 Origin chrome-extension://bmehmboknpnjgjbmiaoidkkjfcgiimbo.

XMLHttpRequest cannot load http://www.google.com/search?hl=en&q=ajax. Origin chrome-extension://bmehmboknpnjgjbmiaoidkkjfcgiimbo is not allowed by Access-Control-Allow-Origin.

我不仅允许向 google.com 发出请求,还允许向任何网站发出请求,但仍然无法通过.有人可以帮忙吗?

I not only allowed request to google.com, but request to any website but still can't get through. Can anybody help?

我的清单文件:

{
  "name": "The popup",
  "version": "0.1",
  "popup": "popup.html",
  "permissions": [
    "http://*/*",
    "https://*/*",
    "https://www.google.com/*",
    "http://www.google.com/*"
    ],
  "browser_action": {
    "default_icon": "clock-19.png",
    "default_title": "This is title",
    "default_popup": "popup.html"
  }
}

实际调用:

function sendRequest() {
    document.write("Sending request");
    var req = new XMLHttpRequest();
      req.open("GET", "http://www.google.com/search?hl=en&q=ajax", true);
      req.onreadystatechange = function() {
          if (req.readyState == 4) {
            if (req.status == 200) {
              alert(req.responseText);
              document.write("OK");
            }
          }
        };
      req.send();
} 

推荐答案

两件事;您需要确保您正在制作打包的应用程序/扩展程序,而不是托管的应用程序/扩展程序.跨源请求不适用于托管应用程序.假设您确定了该部分,您可能想尝试将以下内容放入您的权限中: http://*/ .这是我的一个打包应用程序中唯一的一个,它确实可以毫无问题地跨源应用.

Two things; you need to make sure you are making a packaged app/extension and not a hosted one. Cross origin requests will not work with hosted apps. Assuming you got that part pinned down, you may want to try to put the following into your permissions: http://*/ . That's the only one I have for one of my packaged apps, and it does cross origin stuff without any problems.

这篇关于chrome 扩展中的跨域 XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆