我在实现我的第一个 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 header 。这解释了错误消息。
然而看完this tutorial我的意思是授权 header 应该包含在请求中,因为我将域添加到 manifest.json 文件中。
那么我该如何为这个 http 请求提供身份验证 header 呢?
最佳答案
将您的 XMLHttpRequest 代码从 addratings.js
移动到后台页面。使用 message passing在内容脚本和后台页面之间进行通信(告诉后台页面执行哪个搜索并接收返回的结果)。
关于javascript - Chrome 扩展认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6962308/