2012-03-15 85 views
2

我正在創建一個Disqus通知程序Chrome擴展。這涉及到對disqus.com進行HTTP調用,但我無法通過AJAX調用 - Chrome給我着名的NETWORK_ERR: XMLHttpRequest Exception 101錯誤。Chrome擴展跨域AJAX提供了NETWORK_ERR:XMLHttpRequest異常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調用而丟失了什麼?

回答

7

你有一個錯誤在你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是獲取擴展名中的文件的網址。
http://code.google.com/chrome/extensions/extension.html#method-getURL
你可以從不僅僅是背景頁面(很確定你的擴展中的任何頁面,包括內容腳本)的xhr請求。
Chrome將不會阻止來自未打包擴展程序的xhr呼叫。

+1

這就是我拍我前額的聲​​音。 'getURL'調用是一些早期實驗的遺留問題。謝謝! – 2012-03-15 15:43:29