javascript - Chrome 扩展认证

标签 javascript http google-chrome-extension

我在实现我的第一个 Chrome 扩展程序时遇到了一些困难。我没有太多使用 JavaScript 和 HTTP 的经验,所以如果我没有理解,请原谅。

可以找到 chrome 扩展 here并包含三个文件:addratings.jsicon.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 header 。这解释了错误消息。

然而看完this tutorial我的意思是授权 header 应该包含在请求中,因为我将域添加到 manifest.json 文件中。

那么我该如何为这个 http 请求提供身份验证 header 呢?

最佳答案

将您的 XMLHttpRequest 代码从 addratings.js 移动到后台页面。使用 message passing在内容脚本和后台页面之间进行通信(告诉后台页面执行哪个搜索并接收返回的结果)。

关于javascript - Chrome 扩展认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6962308/

相关文章:

javascript - NestJs - 无法在 RolesGuard 中获取用户上下文

javascript - 在 Chrome 扩展中连接 OpenVPN?

javascript - Chrome 打开包含 url 的选项卡

javascript - JQuery $(window).focusout 问题

javascript - 在 javascript 较多的网站中,如何将用户重定向到不同的页面,同时加载 javascript,而不使用 GET 参数?

Javascript Cookie 函数仅适用于索引文件

javascript - 从 chrome 扩展调用 API 时出现问题

node.js - Nodejs HTTP 和 HTTPS 在同一个端口上

java - URL 请求参数 JSP 错误

javascript - 从 XMLHttpRequest send() 捕获异步网络错误