2011-08-05 144 views
3

我在實施我的第一個Chrome擴展程序時遇到了一些困難。我沒有太多使用JavaScript和HTTP的經驗,所以如果我沒有任何意義,請原諒。Chrome擴展身份驗證

鉻擴展名可以找到here幷包含三個文件:addratings.js,icon.pngmanifest.json

addratings.js看起來是這樣的:

var http = new window.XMLHttpRequest(); 
http.onreadystatechange = function(data) { 
    if (http.readyState == 4) { 
    alert(JSON.stringify(http)); 
    } 
} 
var url = "http://myanimelist.net/api/anime/search.xml?q=Madoka"; 
http.open('GET', url, true); 
http.send(); 

manifest.json文件看起來是這樣的:

{ 
    "name": "Anime Ratings", 
    "version": "1.0", 
    "description": "Shows anime ratings next to anime titles in a Web page.", 
    "permissions": [ 
     "cookies", 
     "http://myanimelist.net/*" 
    ], 
    "content_scripts": [ { 
     "matches": ["http://en.wikipedia.org/wiki/Category:Anime_of_2011"], 
     "run_at": "document_end", 
     "js": ["addratings.js"] 
    } ] 
} 

當我運行該腳本(要this page當它被觸發)HTTP響應我收到看起來像這樣:

{"statusText":"Unauthorized","responseText":"Invalid credentials","response":"Invalid credentials","onabort":null,"readyState":4,"upload":{"onloadstart":null,"onabort":null,"onerror":null,"onload":null,"onprogress":null},"onerror":null,"status":401,"responseXML":null,"onprogress":null,"onload":null,"withCredentials":false,"onloadstart":null,"responseType":""} 

我使用Wireshark捕獲了我的HTTP請求,並確認'授權'HTTP標頭丟失。這解釋了錯誤信息。

但是,在閱讀this tutorial之後,我得到了認證頭應該包含在請求中的表達式,因爲我將該域添加到了manifest.json文件中。

那麼如何爲這個http請求提供身份驗證頭?

回答

2

將您的XMLHttpRequest代碼從addratings.js移到後臺頁面。使用message passing在內容腳本和後臺頁面之間進行通信(以告知後臺頁面執行哪個搜索並接收結果)。

相關問題