Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 634
user3330840 Avatar asked Oct 27 '25 13:10

user3330840


1 Answers

Changes:

  • Replace urlFilter: '<all_urls>' with urlFilter: '*', because <all_urls> is not a supported construct in urlFilter. See chrome.declarativeNetRequest > RuleCondition > urlFilter
  • Add resourceTypes: [ '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);
});
like image 176
Thomas Mueller Avatar answered Oct 30 '25 04:10

Thomas Mueller