I'm creating a Disqus notifier Chrome extension. This involves making an HTTP call to disqus.com, but I can't get the AJAX call through - Chrome gives me the famous NETWORK_ERR: XMLHttpRequest Exception 101
error.
I read somewhere (can't recall where) that Chrome will block cross-domain AJAX calls from unpacked extension, so I've also tried packing my extension - but same result. I also understand that I can't do cross-domain AJAX from anywhere but a background page.
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>
The xhr.send(null);
line is what logs the 101
error. In the event handler handleStateChange
, this.responseText
is an empty string, causing JSON.parse
to fail with Unexpected end of input
.
So: What am I missing in order to be allowed to make cross-domain AJAX calls?