chrome.declarativeNetRequest.getDynamicRules 使用方法

在 extension 裡 chrome.declarativeNetRequest 的使用方法:
https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest

rulesets 有3種

There are three types of rulesets, managed in slightly different ways.

  • Dynamic
    Persist across browser sessions and extension upgrades and are managed using JavaScript while an extension is in use.
  • Session
    Cleared when the browser shuts down and when a new version of the extension is installed. Session rules are managed using JavaScript while an extension is in use.
  • Static
    Packaged, installed, and updated when an extension is installed or upgraded. Static rules are stored in JSON-formatted rule files and listed in the manifest file.

在使用 Dynamic 會遇到的問題就是, Persist, 在 reload extension 時, Persist 的值還有保留, 所以如果同時做2次 addRules, 就會顯示錯誤訊息:

Unchecked runtime.lastError: Rule with id 1 does not have a unique ID.

網路上的範例

chrome.declarativeNetRequest API如何使用?
https://juejin.cn/post/7131360582325780510

chrome extensions插件通过点击按钮修改浏览器UserAgent,manifest v3版本
https://blog.csdn.net/weixin_44786530/article/details/128848739

Chrome 官方範例:
https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest#update-dynamic-rule-examples

Update dynamic rules

The following example shows how to call updateDynamicRules(). The procedure for updateSessionRules() is the same.

// Get arrays containing new and old rules
const newRules = await getNewRules();
const oldRules = await chrome.declarativeNetRequest.getDynamicRules();
const oldRuleIds = oldRules.map(rule => rule.id);

// Use the arrays to update the dynamic rules
await chrome.declarativeNetRequest.updateDynamicRules({
  removeRuleIds: oldRuleIds,
  addRules: newRules
});

如果, 直接把上面的 code 貼到 background.js 會有 2個錯, 就是無法直接使用 await, 所以要把 await 拿掉, 但是拿掉後, 還有會新的錯誤訊息:

Uncaught TypeError: oldRules.map is not a function

問題是同一個原因, 就是 promise 造成的. 解法是使用 .then() 來解決:

How Can I Access The Value Of A Promise?
https://stackoverflow.max-everyday.com/2024/01/how-can-i-access-the-value-of-a-promise/

mozilla 官方教學: declarativeNetRequest.updateDynamicRules
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/declarativeNetRequest/updateDynamicRules

mozilla source code 範例:

let updatedRules = browser.declarativeNetRequest.updateDynamicRules(
    options                // object
);

mozilla 完整範例:
https://github.com/mdn/webextensions-examples/tree/main/dnr-dynamic-with-options

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *