2011-08-05 142 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在内容脚本和后台页面之间进行通信(以告知后台页面执行哪个搜索并接收结果)。

相关问题