0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Chrome Extension MV3】fetch の Header Referer を設定する方法

Posted at

Chrome Extension 内で実行される fetch の Header に Referer を設定したかった。
GoogleとかChatgptとか使って調べまくったけど、全然できなくてハマった。

不幸な人を増やしてはいけないと思ったのでSEOが強いQiitaにメモっておきます。

chrome.webRequest.onBeforeRequest.addListener(() => {
    const rules = [
      {
        id: 1,  
        priority: 1,
        action: {
          type: 'modifyHeaders',
          requestHeaders: [
            {
              header: 'Referer',  
              operation: 'set',
              value: 'https://foo.com/'  
            }
          ]
        },
        condition: {
          urlFilter: 'https://bar.com/*' 
        }
      }
    ];
  
    chrome.declarativeNetRequest.updateDynamicRules({
      removeRuleIds: [1], 
      addRules: rules 
    }, () => {
      if (chrome.runtime.lastError) {
        console.error('Failed to set rules: ' + chrome.runtime.lastError.message);
      } else {
        console.log('Rules have been successfully set.');
      }
    });
  },{urls: ["https://bar.com/*"]});
  • manifest.json の permissions に webRequest, declarativeNetRequest を忘れず追加する。
  • このコードだとリクエスト発生の度にルールを設定するようになっている(開発用)
  • リリース版は onStartup, onInstalled のタイミングで addListener すればいいと思う。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?