Chrome扩展程序未关闭

时间:2014-05-24 10:50:07

标签: javascript google-chrome google-chrome-extension

我目前正在创建一个Chrome扩展程序,可以重定向用户,并在有人输入chrome中的特定网址时添加参数。

所有内容都按预期工作,但扩展程序在关闭后仍然执行重定向(通过图标切换时)。

我的代码出了什么问题?

的manifest.json

{
  "name": "Country Switcher",
  "description": "Redirect Google to a different host",
  "version": "1.0",
  "manifest_version": 2,
  "browser_action": {
      "default_icon": "off.png",
      "default_title": "icon"
    },
  "background": {"scripts":["background.js"]},
  "permissions": [
    "webRequest",
    "*://*/*",
    "webRequestBlocking"
  ]
}

background.js

var host_fr = "https://www.google.fr";
var param_fr = "";
var toggle = false;

chrome.browserAction.onClicked.addListener(function(tab) {
  toggle = !toggle;
  if(toggle){
    chrome.browserAction.setIcon({path: "on.png"});
    chrome.webRequest.onBeforeRequest.addListener(
    function redirect(details) {
         return {redirectUrl: host_fr + details.url.match(/^https?:\/\/[^\/]+([\S\s]*)/)[1] + param_fr};
    },
    {
        urls: [
            "*://www.google.com/*",
        ],
        types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
    },
    ["blocking"]
    );  
}
  else{
    chrome.browserAction.setIcon({path: "off.png"});
  }
});

非常感谢你

PS:我是初学者......

1 个答案:

答案 0 :(得分:3)

您正在添加一个侦听器,并且无需执行任何操作删除

这里有两条可能的路径:

  1. onClicked

    时删除toggle === false处理程序中的侦听器
    function handler(details) { // Must be non-anonymous
      return {redirectUrl: host_fr + details.url.match(/^https?:\/\/[^\/]+([\S\s]*)/)[1] + param_fr};
    }
    
    chrome.browserAction.onClicked.addListener(function(tab) {
      toggle = !toggle;
      if(toggle){
        chrome.browserAction.setIcon({path: "on.png"});
        chrome.webRequest.onBeforeRequest.addListener(
          handler, /* your other parameters */
        );
      }
      else{
        chrome.browserAction.setIcon({path: "off.png"});
        chrome.webRequest.onBeforeRequest.removeListener(handler);
      }
    });
    

    考虑到复杂removeListener,我并非100%确定webRequest如何与addListener一起使用,但这是理论

  2. 修改听众(只添加一次!)以考虑toggle

    function handler(details) {
      if (toggle) {
        return {redirectUrl: host_fr + details.url.match(/^https?:\/\/[^\/]+([\S\s]*)/)[1] + param_fr};
      } else {
        return {}; // do nothing
      }
    }
    
    // Do this at the top level
    chrome.webRequest.onBeforeRequest.addListener(
      handler, /* your other parameters */
    );     
    
    chrome.browserAction.onClicked.addListener(function(tab) {
      toggle = !toggle;
      if (toggle) {
        chrome.browserAction.setIcon({path: "on.png"});
      } else {
        chrome.browserAction.setIcon({path: "off.png"});
      }
    });           
    

    此方法更容易