動態

詳情 返回 返回

chrome插件實現監聽ajax請求,然後修改請求參數 - 動態 詳情

1 修改manifast.json
manifest_version必須為3,因為這個declarativeNetRequest是3中新增的api

{
  "manifest_version": 3,
  "permissions": ["declarativeNetRequest"],
  "host_permissions": ["<all_urls>"]
}

2 在background.js中添加監聽請求的代碼

const RULE_ID = 1;
chrome.declarativeNetRequest.updateDynamicRules({
  // removeRuleIds用來在添加監聽時避免重複監聽,也就是預先刪除同樣id的規則
  removeRuleIds: [RULE_ID],
  addRules: [{
    id: RULE_ID,
    // 定義需要攔截的請求
    condition: {
      urlFilter: "https://apiv3.shanbay.com/news/user_articles?list_type=liked&ipp=10",
      resourceTypes: [chrome.declarativeNetRequest.ResourceType.XMLHTTPREQUEST]
    },
    // 攔截到目標請求後的操作定義
    action: {
      // chrome不允許直接修改初始請求,而是通過重發一次修改後的請求,所以你會看到action.type為REDIRECT
      type: chrome.declarativeNetRequest.RuleActionType.REDIRECT,
      redirect: {
        transform: {
          queryTransform: {
            // 將url中的ipp參數的值改成了100
            addOrReplaceParams: [{ key: "ipp", value: "100" }]
          }
        }
      }
    },
  }]
});

3 驗收效果
初始的請求1被Redirect掉了,請求2如預期的返回了結果,原先的業務流程也沒有被重定向打斷,非常棒
image.png
image.png

user avatar Leesz 頭像 linlinma 頭像 dawanzi_6278b06ec111c 頭像 solvep 頭像 ccVue 頭像 xw-01 頭像 haixiudezhusun 頭像 b_a_r_a_n 頭像 heath_learning 頭像 feixi50 頭像 wojiaocuisite 頭像 wuyagege 頭像
點贊 39 用戶, 點贊了這篇動態!
點贊

Add a new 評論

Some HTML is okay.