Chrome extension authentication
I'm having some difficulty implementing my first Chrome Extension. I don't have much experience using JavaScript and HTTP so please be forgiving if I'm making no sense.
The chrome extension can be found here and contains three files: addratings.js
, icon.png
and manifest.json
.
The addratings.js
looks like this:
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();
The manifest.json
file looks like this:
{
"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":开发者_如何学Python "document_end",
"js": ["addratings.js"]
} ]
}
When I run the script (it is triggered when going to this page) the http response I receive looks like this:
{"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":""}
I captured my HTTP request with Wireshark and confirmed that the 'Authorization' HTTP header was missing. Which explains the error message.
However, after reading this tutorial I was under the expression that the authorization header should have been included in the request because I added the domain to the manifest.json file.
So how do I provide the authentication headers to this http request?
Move your XMLHttpRequest code from addratings.js
to a background page. Use message passing to communicate between a content script and a background page (to tell background page which search to execute and receive results back).
精彩评论