chrome.declarativeNetRequest

官方地址:https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/

静态:

background.js

chrome.declarativeNetRequest.getEnabledRulesets(rulesetIds => console.log(rulesetIds));

manifest.json

{
  "manifest_version": 3,
  "name": "declarativeNetRequest-sample-static",
  "version": "0.0.1",
  "permissions": [
    "declarativeNetRequest",
    "declarativeNetRequestFeedback"
  ],
  "host_permissions": [
    "https://www.google.com/*"
  ],
  "declarative_net_request": {
    "rule_resources": [{
      "id": "ruleset1",
      "enabled": true,
      "path": "ruleset1.json"
    }]
  },
  "background": {
    "service_worker": "background.js"
  }
}

ruleset1.json:

[
  {
    "id": 1,
    "priority": 1,
    "condition": {
      "domains": ["www.google.com"],
      "resourceTypes": ["main_frame", "xmlhttprequest"]
    },
    "action": {
      "type": "modifyHeaders",
      "requestHeaders": [{
        "header": "X-DeclarativeNetRequest-Sample",
        "operation": "set",
        "value": "request"
      }],
      "responseHeaders": [{
        "header": "X-DeclarativeNetRequest-Sample",
        "operation": "set",
        "value": "response"
      }]
    }
  }
]

动态:

manifest.json

{
  "manifest_version": 3,
  "name": "declarativeNetRequest-sample-dynamic",
  "version": "0.0.1",
  "permissions": [
    "declarativeNetRequest",
    "declarativeNetRequestFeedback"
  ],
  "host_permissions": [
    "https://www.google.com/*"
  ],
  "background": {
    "service_worker": "background.js"
  }
}

 

file:

const ruleId = 1;

const rules = {
  removeRuleIds: [ruleId],
  addRules: [{
    id: ruleId,
    priority: 1,
    condition: {
      domains: ["www.google.com"],
      resourceTypes: ["main_frame", "xmlhttprequest"],
    },
    action: {
      type: "modifyHeaders",
      requestHeaders: [{
        header: "X-DeclarativeNetRequest-Sample",
        operation: "set",
        value: "request"
      }],
      responseHeaders: [{
        header: "X-DeclarativeNetRequest-Sample",
        operation: "set",
        value: "response"
      }],
    }
  }],
};

chrome.declarativeNetRequest.updateDynamicRules(rules, () => {
  if (chrome.runtime.lastError) {
    console.error(chrome.runtime.lastError);
  } else {
    chrome.declarativeNetRequest.getDynamicRules(rules => console.log(rules));
  }
});

 

posted @ 2022-06-30 10:18  冰糖葫芦很乖  阅读(2606)  评论(1编辑  收藏  举报