我在实施第一个Chrome扩展程序时遇到了一些困难。我没有太多使用JavaScript和HTTP的经验,所以如果我没有意义,请原谅。
可以找到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请求,并确认缺少“授权”HTTP标头。这解释了错误信息。
但是,在阅读this tutorial之后,我认为授权标题应该包含在请求中,因为我将域添加到manifest.json文件中。
那么如何为此http请求提供身份验证标头?
答案 0 :(得分:2)
将您的XMLHttpRequest代码从addratings.js
移至背景页面。使用message passing在内容脚本和后台页面之间进行通信(告诉后台页面执行哪些搜索并接收结果)。