Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

javascript - Cross-Origin XMLHttpRequest in chrome extensions

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 cannot load http://www.google.com/search?hl=en&q=ajax. Origin chrome-extension://bmehmboknpnjgjbmiaoidkkjfcgiimbo is not allowed by Access-Control-Allow-Origin.

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

My manifest file:

{
  "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"
  }
}

the actual call:

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();
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...