简体   繁体   English

Chrome扩展程序:如何以编程方式更改每个页面请求上的标题?

[英]Chrome Extension: How to change headers on every page request programmatically?

I'm currently developing a Chrome Extension and need to add/change a header value, but only on a specific page. 我目前正在开发Chrome扩展程序,需要添加/更改标头值,但只能在特定页面上。 Something like this: 像这样:

chrome.onPageRequest(function(host) {
    if(host == 'google.com') {
        chrome.response.addHeader('X-Auth', 'abc123');
    }
});

Any help would be greatly appreciated :) 任何帮助将不胜感激 :)

You can use the chrome.webRequest API for that purpose. 您可以为此目的使用chrome.webRequest API You'll need the following: 您将需要以下内容:

  1. Declare the appropriate permissions in your manifest: 在清单中声明适当的权限:

    \n... ...\n"permissions": [ “权限”:[\n    ... ...\n    "webRequest", “ webRequest”,\n    "*://*.google.com/*" “ *://*.google.com/*”\n] ]\n
  2. Register a listener for the chrome.webRequest.onHeadersReceived() event and modify the headers. chrome.webRequest.onHeadersReceived()事件注册一个侦听器并修改标头。 In order to be able to modify the headers, you need to define the 'responseHeaders' extra info (see 3rd arguments of listener function): 为了能够修改标题,您需要定义'responseHeaders'额外信息(请参阅listener函数的第3个参数):

    \nchrome.webRequest.onHeadersReceived.addListener(function(details) { chrome.webRequest.onHeadersReceived.addListener(function(details){\n    console.log(details); console.log(详细信息);\n    details.responseHeaders.push({ details.responseHeaders.push({\n        name: 'X-Auth', 名称:“ X-Auth”,\n        value: 'abc123' 值:“ abc123”\n    }); });\n    return { responseHeaders: details.responseHeaders }; 返回{responseHeaders:details.responseHeaders};\n}, { },{\n    urls: ['*://*.google.com/*'] 网址:['*://*.google.com/*']\n}, [ },[\n    "responseHeaders" “ responseHeaders”\n]); ]);\n
  3. Keep in mind that the webRequest permission only works if your background-page is persistent, so remove the corresponding line from your manifest (if it exists - which it should): 请记住,仅当您的背景页面具有持久性时, webRequest权限才有效,因此请从清单中删除相应的行(如果存在的话-应该这样做):

    \n... ...\n"background": { “背景”: {\n    "persistent": false, // <-- Remove this line or set it to `true` “ persistent”:false,// <-删除此行或将其设置为`true`\n    "scripts": [...] “脚本”:[...]\n    ... ...\n

Also, keep in mind that pretty often Google redirects requests based on the user's country (eg redirecting www.google.com to www.google.gr ), in which case the filter will not let them reach your onHeadersReceived listener. 另外,请记住,Google通常会根据用户所在的国家/地区重定向请求(例如,将www.google.com重定向到www.google.gr ),在这种情况下,过滤器将不允许它们到达您的onHeadersReceived侦听器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM