我在实现我的第一个Chrome扩展时遇到了一些困难。我没有太多的使用JavaScript和超文本传输协议的经验,所以如果我说的没有意义,请原谅。
chrome扩展可以在here中找到,它包含三个文件:addratings.js、icon.png和manifest.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请求,并确认'Authorization‘HTTP头丢失了。这解释了错误消息。
然而,在阅读this tutorial之后,我认为authorization头应该包含在请求中,因为我向manifest.json文件中添加域。
那么我该如何向这个http请求提供身份验证头呢?
发布于 2011-08-06 05:00:33
将addratings.js中的XMLHttpRequest代码移到后台页面。使用message passing在内容脚本和后台页面之间进行通信(告知后台页面执行哪个搜索并接收返回的结果)。
https://stackoverflow.com/questions/6962308
复制相似问题