chrome.declarativeNetRequest.getDynamicRules 使用方法

Posted in :

在 extension 裡 chrome.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如何使用?

chrome extensions插件通过点击按钮修改浏览器UserAgent,manifest v3版本

Chrome 官方範例:

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 = =>;

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

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

Uncaught TypeError: is not a function

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

How Can I Access The Value Of A Promise?

mozilla 官方教學: declarativeNetRequest.updateDynamicRules

mozilla source code 範例:

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

mozilla 完整範例:


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