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?
Changes:
urlFilter: '<all_urls>' with urlFilter: '*', because <all_urls> is not a supported construct in urlFilter. See chrome.declarativeNetRequest > RuleCondition > urlFilterresourceTypes: [ 'main_frame' ] to the RuleCondition. Maybe you need to add other resource types, depending on the websites where you're using the extension. But "main_frame" is enough for https://www.whatismybrowser.com/detect/what-is-my-user-agent/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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With