gpt4 book ai didi

javascript - Chrome 扩展跨域 AJAX 给出 NETWORK_ERR : XMLHttpRequest Exception 101

转载 作者:行者123 更新时间:2023-12-02 07:42:26 25 4
gpt4 key购买 nike

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

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

list .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.parse 失败并返回 Unexpected end of input.

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

最佳答案

你的 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 调用。

关于javascript - Chrome 扩展跨域 AJAX 给出 NETWORK_ERR : XMLHttpRequest Exception 101,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9722472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com