Stories

Detail Return Return

chrome插件實現監聽ajax請求,然後修改請求參數 - Stories Detail

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 Avatar linlinma Avatar dawanzi_6278b06ec111c Avatar solvep Avatar ccVue Avatar xw-01 Avatar haixiudezhusun Avatar b_a_r_a_n Avatar heath_learning Avatar feixi50 Avatar wojiaocuisite Avatar wuyagege Avatar
Favorites 39 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.