Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declarativeNetRequest update rules

As described into the documentation I'm trying to update declarativeNetRequest rules of a chrome extension. From the docs:

updateDynamicRules

chrome.declarativeNetRequest.updateDynamicRules(array of integer ruleIdsToRemove, array of Rule rulesToAdd, function callback)

Modify the current set of dynamic rules for the extension. The rules with IDs listed in ruleIdsToRemove are first removed, and then the rules given in rulesToAdd are added. This update happens as a single atomic operation: either all specified rules are added and removed, or an error is returned. These rules are persisted across browser sessions and across extension updates. Any ids in ruleIdsToRemove that are not present will be ignored. Note that static rules specified as part of the extension package can not be removed using this function. Note: MAX_NUMBER_OF_DYNAMIC_RULES is the maximum number of dynamic rules an extension can add.

It's not clear what is intended for dynamic rule. This api will rely on a static rule set that can't be modified until an extension is updated and the method described into the documentation says that the rules shipped with the extension will not be removed from the function.

My question is, how I really can update the rules after I get new rules from an online api? The declarativeNetRequest api didn't provide any method to do this, all the methods provided will not be useful for this scope.

like image 936
miko Avatar asked Jun 10 '26 20:06

miko


2 Answers

After I spent some time figuring out how the chrome.declarativeNetRequest.updateDynamicRules() API works, I ended up with this solution. blockUrls is an array variable that holds all blocked websites/URLs.

blockUrls.forEach((domain, index) => {
  let id = index + 1;

  chrome.declarativeNetRequest.updateDynamicRules({
    addRules: [{
      "id": id,
      "priority": 1,
      "action": { "type": "block" },
      "condition": { "urlFilter": domain, "resourceTypes": ["main_frame"] }
    }],
    removeRuleIds: [id]
  });
});
like image 128
Chi Avatar answered Jun 13 '26 11:06

Chi


Create an array with all your new rules. Get the old rules and replace them all with the new rules.

const newRules = [];
blockUrls.forEach((domain, index) => {
  newRules.push({
    "id": index + 1,
    "priority": 1,
    "action": { "type": "block" },
    "condition": { "urlFilter": domain, "resourceTypes": ["main_frame"] }
  });
});

chrome.declarativeNetRequest.getDynamicRules(previousRules => {
  const previousRuleIds = previousRules.map(rule => rule.id);
  chrome.declarativeNetRequest.updateDynamicRules({
    removeRuleIds: previousRuleIds,
    addRules: newRules
  });
});
like image 38
Wizard Avatar answered Jun 13 '26 09:06

Wizard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!