我正在努力建立我的第一个镀铬扩展,我得到了几乎完成的东西!然而,我已经陷入了最后一部分,即创建一个简单的html切换以暂时禁用扩展。基本上,它的功能类似于广告拦截器,而不是阻止广告阻止网站并将其重定向到特定网址。
这是我尝试使用的代码,但由于某种原因,它将切换启用禁用,但它不会关闭重定向。该应用程序的功能现在完美无缺,我只想打开和关闭它。
的manifest.json
{
"manifest_version": 2,
"name": "Purge",
"description": "Why Use Anything But Google?",
"version": "1.0.0",
"icons": {"128":"icon_128.png"},
"browser_action": {"default icon": "icon.png",
"default_popup": "popup.html"},
"permissions": ["webRequest", "webRequestBlocking", "http://*/", "https://*/"],
"background": {"scripts": ["blocked_domains.js", "background.js"]}
}
popup.html
<html>
<head>
<script src="toggle.js"></script>
</head>
<body>
<h3>PURGE!</h3>
<input type="button" id="toggle_button" value="Disable" />
<hr>
</body>
</html>
background.js
var enabled = true;
chrome.webRequest.onBeforeRequest.addListener(
function(info) {
var url = "https://www.google.com/";
return {redirectUrl: url};
},
{urls: blocked_domains},
["blocking"]);
toggle.js
window.onload = function () {
function updateLabel() {
var enabled = chrome.extension.getBackgroundPage().enabled;
document.getElementById('toggle_button').value = enabled ? "Disable" : "Enable";
}
document.getElementById('toggle_button').onclick = function () {
var background = chrome.extension.getBackgroundPage();
background.enabled = !background.enabled;
updateLabel();
};
updateLabel();
}
好吧,你正在切换布尔值enabled
和按钮,但是无论值如何,你仍然会重定向。
在onBeforeRequest
监听器内部,在决定重定向之前,检查enabled
的值是否为true
的false
:
chrome.webRequest.onBeforeRequest.addListener(
function(info) {
if(!enabled) // if the extension is not enabled
return { cancel: false }; // don't cancel or redirect
var url = "https://www.google.com/";
return { redirectUrl: url };
},
{urls: blocked_domains},
["blocking"]);