我想让我们的declarativeNetRequest
API重定向用户到youtube当他们试图加载amazon.com时. 当我调试我的代码,我没有得到任何问题,但不幸的是,它不是在浏览器工作。对于为什么会这样,任何建设性的意见都将是非常感谢的。
Manifest.json
file:
{
"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.js
file:
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。- 舱单中
background
部分。Json错误。它应该是这样的:
"background": {
"service_worker": "background.js"
},
host_permissions
与站点不匹配。使用"*://www.amazon.com/"
, youtube也一样。- 规则id必须为数字。
- 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/'
}
}],
});
});
另一个解决方案是使用静态规则:
- 从清单中删除
background
section。 - 将此添加到manifest.json中:
"declarative_net_request": { "rule_resources" : [{ "id": "ruleset_1", "enabled": true, "path": "rules.json" }] },
- 创建rules.json:
[{ "id": 1, "condition": { "urlFilter": "|https://www.amazon.com/" }, "action": { "type": "redirect", "redirectUrl": "https://www.youtube.com/" } }]