Search code examples
javascripttypescriptgoogle-chrome-extensionchromiumchrome-extension-manifest-v3

Chrome Extension Manifest Version 3 custom user agent is not getting set


We have an extension with only 2 files: manifest.json and background.js

The browser (chrome version 112) doesn't report any error, but the user agent is not getting set to `my-custom-user-agent. Here is the complete extension code:

manifest.json

{
    "name": "ua-customizer",
    "version": "1",
    "manifest_version": 3,
    "permissions": [
      "declarativeNetRequest"
    ],
    "host_permissions": [
      "<all_urls>"
    ], 
    "background": {
      "service_worker": "background.js"
    }
  }

background.js

const rules = {
  removeRuleIds: [1],
  addRules: [
    {
      id: 1,
      priority: 1,
      action: {
        type: 'modifyHeaders',
        requestHeaders: [
          {
            header: 'user-agent',
            operation: 'set',
            value: `my-custom-user-agent`,
          },
        ],
      },
      condition: {
        urlFilter: '<all_urls>'
      },
    },
  ],
}
chrome.declarativeNetRequest.updateDynamicRules(rules);

What is it missing?


Solution

  • Changes:

    Changed code:

    condition: {
        resourceTypes: [ 'main_frame' ],
        urlFilter: '*'
    },
    

    Both changes are necessary.
    If you make only one of the changes, the extension will not modify the user-agent string.

    Also, chrome.declarativeNetRequest.updateDynamicRules(rules); only needs to be executed once.
    See chrome.declarativeNetRequest > updateDynamicRules: "These rules are persisted across browser sessions and across extension updates."
    I recommend putting it in a chrome.runtime.onInstalled handler:

    chrome.runtime.onInstalled.addListener(function(details) {
        chrome.declarativeNetRequest.updateDynamicRules(rules);
    });