【发布时间】: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.parse 以Unexpected end of input 失败。
那么:为了被允许进行跨域 AJAX 调用,我缺少什么?
【问题讨论】:
标签: javascript ajax google-chrome-extension cross-domain