GoogleChrome / chrome-extensions-samples

Chrome Extensions Samples
https://developer.chrome.com/docs/extensions
Apache License 2.0
15.59k stars 8.28k forks source link

Chrome. webRequest. onBeforeSendHeaders. addListener cannot modify request headers #980

Open slongzhang opened 1 year ago

slongzhang commented 1 year ago
{
    "manifest_version": 3,
    "name": "webpack dev chrome extension MV3",
    "version": "1.0.1",
    "description": "a chrome extension with webpack@3.6",
    "background": {
        "service_worker": "background/index.js",
        "type": "module"
    },
    "permissions": [ "tabs"
        , "storage"
        , "cookies"
        , "alarms"
        , "scripting"
        , "webRequest"
        , "declarativeNetRequest"
        , "declarativeNetRequestWithHostAccess"
        , "declarativeNetRequestFeedback"
    ],
    "declarative_net_request": {
        "rule_resources": []
    },
    "web_accessible_resources": [],
    "homepage_url": "https://www.slong.ink",
    "update_url": "https://clients2.google.com/service/update2/crx"
}
// 获取全局变量
const slongThis = (typeof window !== 'undefined'
   ? window
   : (typeof process === 'object' &&
      typeof require === 'function' &&
      typeof global === 'object')
     ? global
     : this)

const config = {
  manifest: {},
  crxId: null,
  crxUrl: null,

  prefix: '__ZSL__',
  globalThis: slongThis
}

try { 
  if (typeof chrome.runtime.getManifest === 'function') {
    config.manifest = chrome.runtime.getManifest()
    const extensionUrl = chrome.runtime.getURL('') // 获取插件的根路径
    const extensionId = new URL(extensionUrl).host;
    config.crxId = extensionId;
    config.crxUrl = extensionUrl;
  }
} catch(e) {

}
// slongThis.config = config

const extraInfo = ["requestHeaders"];
if (chrome.webRequest.OnBeforeSendHeadersOptions.EXTRA_HEADERS) {
  extraInfo.push(chrome.webRequest.OnBeforeSendHeadersOptions.EXTRA_HEADERS)
}

// 设置请求头修改
chrome.webRequest.onBeforeSendHeaders.addListener(function(details) {
  console.log(details)
  // if (details.tabId != -1 || !details.initiator.includes(config.crxId)) {
  //   return {requestHeaders: details.requestHeaders};
  // }
  let requestHeaders = function(rh) {
    let headers = {}, customHeaders = {};
    for (let item of rh) {
      if(item.name.indexOf(config.prefix) === 0) {
          item.name = item.name.substr(7);
          customHeaders[item.name] = item;
          customHeaders['aaa'] = item;
      } else {
          headers[item.name] = item;
      }
    }
    for (let [key, item] of Object.entries(customHeaders)) {
      headers[key] = customHeaders[item.name]
    }
    return Object.values(headers);
  }(details.requestHeaders);

  return {requestHeaders}
}, {
  tabId: -1,
  urls: ['*://*/*'],
  types: ['xmlhttprequest']
}, extraInfo)

fetch("https://www.bing.com", {
  "headers": {
    "__ZSL__Origin": "https://www.google.com",
    "accept": "*/*",
    "accept-language": "zh-CN,zh;q=0.9",
    "content-type": "application/x-www-form-urlencoded",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "none"
  },
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": null,
  "method": "POST",
  "mode": "cors",
  "credentials": "include"
});

image image

arjanvillon commented 1 year ago

@slongzhang were you able to figure this out?

tophf commented 1 year ago

This repository is for samples, not for problems with the API.

As for the problem, you can't use webRequest in a normal ManifestV3 extension to modify the requests. This is by design and you need to use chrome.declarativeNetRequest, which unfortunately is too dumb for your use case. So, your only solutions are 1) ExtensionInstallForcelist or 2) running chrome --allowlisted-extension-id=YOUR_EXT_ID. Both enable the use of webRequestBlocking permission with 'blocking' in extraInfo for addListener, which is required to modify requests.