Chrome扩展程序代码在弹出窗口中打开和关闭我的扩展程序

问题描述 投票:1回答:1

我正在努力建立我的第一个镀铬扩展,我得到了几乎完成的东西!然而,我已经陷入了最后一部分,即创建一个简单的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();
}
javascript html google-chrome-extension manifest.json
1个回答
1
投票

好吧,你正在切换布尔值enabled和按钮,但是无论值如何,你仍然会重定向。

onBeforeRequest监听器内部,在决定重定向之前,检查enabled的值是否为truefalse

 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"]);
© www.soinside.com 2019 - 2024. All rights reserved.