chrome-extensions-samples icon indicating copy to clipboard operation
chrome-extensions-samples copied to clipboard

example on declarativeNetRequest and how to use it to redirect url

Open Koushikphy opened this issue 2 years ago • 4 comments

Koushikphy avatar Jan 17 '22 15:01 Koushikphy

manifest.json

{
  "name": "My extension",
  "manifest_version": 3,
  "version": "1.0",
  "declarative_net_request" : {
    "rule_resources" : [{
      "id": "ruleset_1",
      "enabled": true,
      "path": "rules_1.json"
    }]
  },
  "permissions": [
    "declarativeNetRequest",
    "declarativeNetRequestFeedback"
  ],
  "host_permissions": [
    "*://google.com/*",
    "*://microsoft.com/*"
  ]
}

rules_1.json

[ 
  {
    "id": 1,
    "priority": 1,
    "action": { "type": "redirect", "redirect":  { "url": "https://example.com" } },
    "condition": { "urlFilter": "microsoft.com", "resourceTypes": ["main_frame"] }
  }, 
  {
    "id": 2,
    "priority": 1,
    "action": { "type": "redirect", "redirect": { "extensionPath": "/test.txt" } },
    "condition": { "urlFilter": "google.com", "resourceTypes": ["main_frame"] }
  }
]

test.txt

123

guest271314 avatar Feb 10 '22 03:02 guest271314

  chrome.declarativeNetRequest.updateDynamicRules({
    addRules: [{
      'id': 1001,
      'priority': 1,
      'action': {
        'type': 'redirect',
        'redirect': {
          url: 'https://www.facebook.com'
        }
      },
      'condition': {
        'urlFilter': 'https://www.twitter.com',
        'resourceTypes': [
          'csp_report', 'font', 'image', 'main_frame', 'media', 'object', 'other', 'ping', 'script',
          'stylesheet', 'sub_frame', 'webbundle', 'websocket', 'webtransport', 'xmlhttprequest'
        ]
      }
    }],
   removeRuleIds: [1001]
  })
}

femvc avatar Apr 12 '22 05:04 femvc

Do you know how to count number of blocked request ? I don't see it in the documentation. Thanks

brunovu20 avatar Aug 18 '22 19:08 brunovu20

@brunovu20 Include this in manifest.json

  "permissions": [
    "declarativeNetRequest",
    "declarativeNetRequestFeedback"
  ]

You should be able to just create a variable and increment each time the event https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#event-onRuleMatchedDebug fires

let n = 0;
chrome.declarativeNetRequest.onRuleMatchedDebug.addListener(
  (e) => console.log(e, ++n)
);

guest271314 avatar Aug 20 '22 01:08 guest271314

[
    {
        "id": 2,
        "priority": 1,
        "action": {
          "type": "modifyHeaders",
          "responseHeaders": [
         
            { "header": "first", "operation": "set", "value": "*" },
            { "header": "second", "operation": "set", "value": "*" },
            { "header":"third":"set","value":"true" }
          ]
        },
        "condition": { "urlFilter": "|http*", "resourceTypes": ["main_frame"] }
      }
]

does not work. request works

amervelic avatar Oct 21 '22 15:10 amervelic

[
    {
        "id": 2,
        "priority": 1,
        "action": {
          "type": "modifyHeaders",
          "responseHeaders": [
         
            { "header": "first", "operation": "set", "value": "*" },
            { "header": "second", "operation": "set", "value": "*" },
            { "header":"third":"set","value":"true" }
          ]
        },
        "condition": { "urlFilter": "|http*", "resourceTypes": ["main_frame"] }
      }
]

does not work. request works

How and when do you determine the headers were not modified?

guest271314 avatar Oct 22 '22 00:10 guest271314

How and when do you determine the headers were not modified?

You mean a bug in "google dev tools", but that is not the case. This just doesn't work. With other extensions, a change in the response header is visible. WORKS WITH condition xmlhttprequest

amervelic avatar Oct 22 '22 10:10 amervelic

Are you modifying the headers anywhere else in the code?

https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/

If multiple modifyHeaders rules specify the same header, the resulting modification for the header is determined based on the priority of each rule and the operations specified.

  • If a rule has appended to a header, then lower priority rules can only append to that header. set and remove operations are not permitted.
  • If a rule has set a header, then lower priority rules cannot further modify the header, except for append rules from the same extension.
  • If a rule has removed a header, then lower priority rules cannot further modify the header.

guest271314 avatar Oct 22 '22 13:10 guest271314

no.

amervelic avatar Oct 22 '22 14:10 amervelic

Can you kindly post the full code you are testing here?

guest271314 avatar Oct 22 '22 14:10 guest271314

no any code , static ruleset file, manifest, background.js. HOW disable static ruleset ?

{
  "manifest_version": 3,
  "name": "No Name",
  "version": "0.1.1",
  "description": "Nothing",

  "icons": {
    "16": "images/icon_green_16.png",
    "24": "images/icon_green_24.png",
    "48": "images/icon_green_48.png",
    "128": "images/icon_green_128.png"
  },

  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_icon": {
      "16": "images/icon_green_16.png",
      "24": "images/icon_green_24.png",
      "48": "images/icon_green_48.png",
      "128": "images/icon_green_128.png"
    },
    "default_title": "NoName"
   
  },
  "declarative_net_request" : {
    "rule_resources" : [{
      "id": "cors",
      "enabled": false,
      "path": "ruleset_cors.json"
    }]
  },
  "permissions": [
   "storage",
   "activeTab", 
   "declarativeNetRequest" , 
   "declarativeNetRequestFeedback"],
  "host_permissions": ["http://*/", "https://*/"],
  
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "run_at": "document_start",
      "js": ["contentScript.js"]
    }
  ]
}

amervelic avatar Oct 23 '22 14:10 amervelic

I added the ruleset dynamically and now it can be easily removed with a toggle.

amervelic avatar Oct 23 '22 15:10 amervelic

@amervelic The JSON in your rule set is invalid here

{ "header":"third":"set","value":"true" }

should be

{ "header": "third", "operation": "set", "value":"true" }

Your ruleset is also set to

 "enabled": false,

Screenshot of your code, with "enabled" set to true and third rule fixed: Screenshot_2022-10-23_08-24-31

If you are just trying to remove CSP headers you can use https://github.com/guest271314/remove-csp-header.

guest271314 avatar Oct 23 '22 15:10 guest271314

I needed NO CORS headers for my private needs and it only works with the condition "xmlhttprequest". It's enough for me at the moment but...

amervelic avatar Oct 23 '22 15:10 amervelic

Then include "xmlhttprequest". Why the "but..."?

guest271314 avatar Oct 23 '22 15:10 guest271314

example enable/disable static rulesets:

function disableRule() {
  chrome.declarativeNetRequest.updateEnabledRulesets(
    {
      disableRulesetIds: ["ruleset_enable"],
      enableRulesetIds:["ruleset_disable"]
    },
    () => {}
  );
}

function enableRule() {
  chrome.declarativeNetRequest.updateEnabledRulesets(
    {
      enableRulesetIds: ["ruleset_enable"],
      disableRulesetIds: ["ruleset_disable"]
    },
    () => {}
  );
}

amervelic avatar Nov 08 '22 12:11 amervelic

enableRulesetIds:["ruleset_disable"]

did you slove it?

wangsen2020 avatar Nov 08 '22 15:11 wangsen2020

@amervelic The JSON in your rule set is invalid here

{ "header":"third":"set","value":"true" }

should be

{ "header": "third", "operation": "set", "value":"true" }

Your ruleset is also set to

 "enabled": false,

Screenshot of your code, with "enabled" set to true and third rule fixed: Screenshot_2022-10-23_08-24-31

If you are just trying to remove CSP headers you can use https://github.com/guest271314/remove-csp-header.

you try it ? it doesn't work, it still exist in network of chrome console

wangsen2020 avatar Nov 08 '22 15:11 wangsen2020

enableRulesetIds:["ruleset_disable"]

did you slove it?

yes

amervelic avatar Nov 08 '22 15:11 amervelic

enableRulesetIds:["ruleset_disable"]

did you slove it?

yes

Can you share the solution? My responseHeaders cannot be removed, thanks very much!

wangsen2020 avatar Nov 08 '22 16:11 wangsen2020

@brunovu20 Include this in manifest.json

  "permissions": [
    "declarativeNetRequest",
    "declarativeNetRequestFeedback"
  ]

You should be able to just create a variable and increment each time the event https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#event-onRuleMatchedDebug fires

let n = 0;
chrome.declarativeNetRequest.onRuleMatchedDebug.addListener(
  (e) => console.log(e, ++n)
);

onRuleMatchedDebug (as per documentation) works for unpacked extensions ONLY. No way to have the same result in normal (production) extensions?

radiolondra avatar Dec 25 '22 17:12 radiolondra

No way to have the same result in normal (production) extensions?

I generally don't upload or download extensions from Chrome Web Store.

You can simply publish your extension on GitHub - for production.

guest271314 avatar Dec 25 '22 17:12 guest271314

@radiolondra Have you tried using this https://developer.chrome.com/docs/extensions/reference/webRequest/?

guest271314 avatar Dec 25 '22 18:12 guest271314

Closing this as resolved in https://github.com/GoogleChrome/chrome-extensions-samples/pull/839.

oliverdunk avatar Mar 03 '23 15:03 oliverdunk