【问题标题】:Chrome extension cross-domain AJAX gives NETWORK_ERR: XMLHttpRequest Exception 101Chrome 扩展跨域 AJAX 给出 NETWORK_ERR: XMLHttpRequest Exception 101
【发布时间】:2012-04-01 02:56:55
【问题描述】:

我正在创建 Disqus 通知程序 Chrome 扩展程序。这涉及对 disqus.com 进行 HTTP 调用,但我无法通过 AJAX 调用 - Chrome 给了我著名的 NETWORK_ERR: XMLHttpRequest Exception 101 错误。

我在某处(不记得在哪里)读到 Chrome 将阻止来自未打包扩展的跨域 AJAX 调用,因此我也尝试打包我的扩展 - 但结果相同。我也明白,除了后台页面,我无法从任何地方进行跨域 AJAX。

manifest.json:

{
 "name": "Disqus notifier",
 "version": "1.0",
 "description": "Get notifications when you have new replies on your Disqus posts",
 "browser_action": {
   "default_icon": "icon.png",
   "popup": "popup.html"
 },
 "icons": {
    "16": "icon16.png",
    "48": "icon48.png",
    "128": "icon128.png"
 },
 "background_page": "background.html",
  "permissions": [
        "http://*/*",
        "https://*/*"
    ]
}

background.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script type="text/javascript" src="background.js"></script>
</head>
<body>

</body>
</html>

background.js:

function poll() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = handleStateChange; // Implemented elsewhere.
    xhr.open("GET", chrome.extension.getURL('http://disqus.com/api/3.0/messagesx/unread.json?user=<...>&api_key=<...>'), false);
    xhr.send(null);
    console.log(xhr.responseText);
}

function handleStateChange() {
    if (this.readyState == 4) {
        var resp = JSON.parse(this.responseText);
        updateUi(resp);
    }
}

function updateUi(json) {
    console.log("JSON: ", json);
}

popup.html:

<html>
<head>
    <title>Disqus notifier</title>
    <script type="text/javascript">
        function updateButtonClicked() {
            chrome.extension.getBackgroundPage().poll();
        }
    </script>
</head>

<body>
  <button type="button" onclick="updateButtonClicked()">Update</button>
</body>
</html>

xhr.send(null); 行记录了101 错误。在事件处理程序handleStateChange 中,this.responseText 是一个空字符串,导致JSON.parseUnexpected end of input 失败。

那么:为了被允许进行跨域 AJAX 调用,我缺少什么?

【问题讨论】:

    标签: javascript ajax google-chrome-extension cross-domain


    【解决方案1】:

    你的 background.js 中有一个错误....

    xhr.open("GET", chrome.extension.getURL('http://disqus.com/api/3.0/messagesx/unread.json?user=<...>&api_key=<...>'), false);
    

    ……应该是……

    xhr.open("GET", 'http://disqus.com/api/3.0/messagesx/unread.json?user=<...>&api_key=<...>', false);
    

    chrome.extension.getURL 用于获取扩展中文件的 url。
    http://code.google.com/chrome/extensions/extension.html#method-getURL
    您不仅可以从后台页面发出 xhr 请求(现在可以肯定它是您扩展程序中的任何页面,包括内容脚本)。
    Chrome 不会阻止来自未打包扩展程序的 xhr 调用。

    【讨论】:

    • 那是我拍打额头的声音。 getURL 调用是一些早期实验的遗物。谢谢!
    猜你喜欢
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 2013-01-11
    相关资源
    最近更新 更多