declarativeNetRequest更新规则 [英] declarativeNetRequest update rules
问题描述
正如文档中所述,我正在尝试更新Chrome扩展程序的 declarativeNetRequest
规则.从文档中:
updateDynamicRules
chrome.declarativeNetRequest.updateDynamicRules(整数ruleIdsToRemove的数组,Rule rulesToAdd的数组,函数回调)
修改扩展的当前动态规则集.首先删除ruleIdsToRemove中列出的ID的规则,然后添加rulesToAdd中给定的规则.此更新是作为单个原子操作发生的:添加或删除所有指定的规则,或者返回错误.这些规则在浏览器会话和扩展程序更新中均保持不变.ruleIdsToRemove中所有不存在的ID将被忽略.请注意,使用此功能无法删除作为扩展软件包一部分指定的静态规则.注意:MAX_NUMBER_OF_DYNAMIC_RULES是扩展程序可以添加的最大动态规则数.
目前尚不清楚什么是动态规则.该api将依赖于静态规则集,在更新扩展程序之前,该规则集将无法修改,并且文档中描述的方法说,扩展程序附带的规则不会从该函数中删除.
我的问题是,从在线api获取新规则后,如何真正更新规则?declarativeNetRequest api没有提供任何执行此操作的方法,提供的所有方法在此范围内将无用.
花了一段时间弄清楚chrome.declarativeNetRequest.updateDynamicRules()api的工作原理后,我最终解决了这个问题,并且效果很好.
blockUrls是一个数组变量,其中包含所有阻止的网站/网址.
blockUrls.forEach((domain,index)=> {设id = index + 1;chrome.declarativeNetRequest.updateDynamicRules({addRules:[{"id":id,优先级":1,"action":{"type":"block"},"condition":{"urlFilter":域,"resourceTypes":["main_frame"]}}],removeRuleIds:[id]},)})
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.
After I spent sometime to figure out how chrome.declarativeNetRequest.updateDynamicRules() api works, I ended up this solution, and it works fine.
blockUrls is an array variable which holds all block 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]
},
)
})
这篇关于declarativeNetRequest更新规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!