动态

详情 返回 返回

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.