在Chrome扩展中修改响应头

pxy2qtax  于 2023-04-27  发布在  Go
关注(0)|答案(2)|浏览(215)

我尝试用我的Chrome扩展修改referer-policy标头,但它不影响响应标头。
Manifest.json:

{
  "name": "My Example Extension",
  "version": "1.0",
  "description": "",
  "permissions": [
    "webRequest",
    "webRequestBlocking",
    "*://*/*"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": true
  },
  "manifest_version": 2
}

background.js:

chrome.webRequest.onHeadersReceived.addListener(details => {
    let header = details.responseHeaders.find(e => e.name.toLowerCase() === 'referrer-policy');

    // Check if the header has been defined already
    if (typeof header !== 'undefined') {
        console.log ('Modifying header');
        header.value = 'strict-origin';
    }
    else {
        details.responseHeaders.push({ name: 'referrer-policy', value: 'strict-origin' });
    }

    return {responseHeaders: details.responseHeaders};
}, {urls: ["*://*/*"]}, ['blocking', 'responseHeaders']);

我添加了调试输出,显示代码相应地修改或添加了头,但在浏览器本身没有影响。

qpgpyjmq

qpgpyjmq1#

当我试图修改扩展中的响应头时,我正在编写完全相同的代码。

// manifest.json

  "permissions": [
    "webRequest", "webRequestBlocking", "https://developer.chrome.com/*"
  ]

// background.js

chrome.webRequest.onHeadersReceived.addListener(
  function(details) {
    const newHeader = {name:"foo", value:"bar"};
    const responseHeaders = details.responseHeaders.concat(newHeader);
    return { responseHeaders };
  },
  // filters
  {
    urls: ["https://developer.chrome.com/*"],
  },
  // extraInfoSpec
  ["blocking","responseHeaders"]
);

完全不管用。
直到我把最后一个参数改成:

// extraInfoSpec
  ["blocking","responseHeaders", "extraHeaders"]

终于成功了
通过重新访问该文档,在请求生命周期部分的最后几段中:
从Chrome 79开始,...另一方面,响应头修改无法欺骗CORS检查。如果您需要欺骗CORS协议,则还需要为响应修改指定' extraHeaders '。

chhkpiq4

chhkpiq42#

您没有返回修改后的标头。请尝试:

chrome.webRequest.onHeadersReceived.addListener(details => {
    let myResponseHeaders = details.responseHeaders;
    let header = myResponseHeaders.find(e => e.name == 'Referrer-Policy');

    // Check if the header has been defined already
    if (header) {
        console.log ('Modifying header');
        let headerIndex = myResponseHeaders.indexOf(header);
        myResponseHeaders.splice(headerIndex,1);
    }
    
    myResponseHeaders.push({ name: 'Referrer-Policy', value: 'strict-origin' });
    

    return {responseHeaders: myResponseHeaders};
}, {urls: ["*://*/*"]}, ['blocking', 'responseHeaders']);

或者使用从文档中复制的稍微修改的代码:

chrome.webRequest.onHeadersReceived.addListener(
    function(details) {
      for (var i = 0; i < details.responseHeaders.length; ++i) {
        if (details.responseHeaders[i].name === 'Referrer-Policy') {
          details.responseHeaders[i].value = 'strict-origin';
          break;
        }
      }
      return {responseHeaders: details.responseHeaders};
    },
    {urls: ["<all_urls>"]},
    ["blocking", "responseHeaders"]
);

相关问题