声明式网络请求不会重定向请求



我想让我们的declarativeNetRequestAPI重定向用户到youtube当他们试图加载amazon.com时. 当我调试我的代码,我没有得到任何问题,但不幸的是,它不是在浏览器工作。对于为什么会这样,任何建设性的意见都将是非常感谢的。

Manifest.jsonfile:

{
"manifest_version": 3,
"name": "My Extension",
"version": "1.0",
"description": "Honours Project",
"background": {
"service": {
"scripts": ["background.js"],
"type": "service_worker",
"persistent": true
}
},
"permissions": [
"declarativeNetRequest",
"activeTab",
"storage",
"https://www.googleapis.com/",
"webRequest",
"*://amazon.com/*",
"*://youtube.com/*",
"webRequestBlocking"
],
"action": {
"default_icon": "images/zi.png",
"default_title": "My Extension",
"default_popup": "popup.html"
},
"icons": {
"16": "images/zi.png"
}

}

Background.jsfile:

chrome.declarativeNetRequest.addRule({
id: 'redirect-to-youtube',
priority: 100,
condition: {
urlFilter: 'https://www.amazon.com/'
},
action: {
type: 'redirect',
redirectUrl: 'https://www.youtube.com/'
}
}, function() {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
return;
}

// Update the dynamic rules to apply the new rule to all active tabs
chrome.declarativeNetRequest.updateDynamicRules(function() {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
return;
}

console.log('Successfully added declarative rule');
});
});
我添加了一个规则来重定向我的amazonurl到youtubeurl。
  1. 舱单中background部分。Json错误。它应该是这样的:
"background": {
"service_worker": "background.js"
},
  1. host_permissions与站点不匹配。使用"*://www.amazon.com/", youtube也一样。
  2. 规则id必须为数字。
  3. declarativeNetRequest API没有addRule方法

让我们正确使用updateDynamicRules:

chrome.runtime.onInstalled.addListener(() => {
chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: [1],
addRules: [{
id: 1,
condition: {
urlFilter: '|https://www.amazon.com/'
},
action: {
type: 'redirect',
redirectUrl: 'https://www.youtube.com/'
}
}],
});
});

另一个解决方案是使用静态规则:

  1. 从清单中删除backgroundsection。
  2. 将此添加到manifest.json中:
    "declarative_net_request": {
    "rule_resources" : [{
    "id": "ruleset_1",
    "enabled": true,
    "path": "rules.json"
    }]
    },
    
  3. 创建rules.json:
    [{
    "id": 1,
    "condition": {
    "urlFilter": "|https://www.amazon.com/"
    },
    "action": {
    "type": "redirect",
    "redirectUrl": "https://www.youtube.com/"
    }
    }]