我正在使用我构建的 Chrome 扩展来拦截和重定向页面上加载的一些资产。
为此,我依赖
chrome.webRequest.onBeforeRequest
API,它运行良好。
但是,Google 已宣布将在 2023 年弃用此 API,因此我正在尝试切换到 declarativeNetRequest。
这是我的代码(
tab
指的是当前活动的选项卡,我省略了 redirectionMap
的声明):
async function updateAssetRedirectionRules(redirectionMap, tab) {
// redirectionMap is an array of { originalUrl, newUrl }
let updatedSessionRules = await chrome.declarativeNetRequest.updateSessionRules({
// removing all current rules
removeRuleIds: redirectionMap.map((_, index) => index + 1),
addRules: redirectionMap.map(({ originalUrl, newUrl }, index) => {
return {
"id": index + 1,
"priority": 1,
"action": {
"type": "redirect",
"redirect": {
"url": newUrl
}
},
"condition": {
"urlFilter": originalUrl,
"resourceTypes": ["main_frame"]
}
}
})
})
// store this session so that I don't reset the rules again for the same tab
chrome.storage.local.get(['redirectionSession'], ({ redirectionSession }) => {
redirectionSession = redirectionSession || {}
redirectionSession[tab.id] = updatedSessionRules
chrome.storage.local.set({ redirectionSession })
})
}
页面加载后,从
background.js
中,我会:
chrome.storage.local.get(['redirectionSession'], async ({ redirectionSession }) => {
if (!redirectionSession || !redirectionSession[tab.id]) {
await updateAssetRedirectionRules(redirectionMap, tab)
// refresh the page for the new redirection rules to take effect
chrome.tabs.update(tab.id, {
url: whateverTheCurrentUrlIs
})
} else {
// my new redirection rules are being applied
}
})
如您所见,我正在尝试在第一个页面加载时更新重定向规则,但到那时它们生效为时已晚,因此,我正在刷新页面,希望新的重定向规则能够持续存在并且从加载第二页开始生效。
这是正确的做法吗?