无法删除事件侦听器

时间:2014-07-10 23:17:45

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

尝试使用Chrome扩展程序让我的脚湿透。我创建了一个标签限制器,但它的错误。

我希望点击browser action图标的事件可以打开和关闭扩展程序。我相信我有正确的设置。当切换时,它会从chrome.tabs api创建一个监听器,但是当切换掉时,我很难移除这个监听器。

我已经尝试了StackOverflow上的一些常见答案(如下所示),用于删除侦听器,但没有一个能够正常运行。

以下是background.js

var tabUrls, bookmarkFolder, currentWindow;
var toggle = false;

chrome.browserAction.onClicked.addListener(function(tab){
  toggle = !toggle;

  if(toggle) {
    chrome.browserAction.setBadgeText({"text": "ON"});

    console.log("I'm listening to the browser action");

    runExtension();

  } else {
    console.log("i shouldn't be working now.");

    chrome.browserAction.setBadgeText({"text": ""});

    // Need to remove the listener somehow.  This isn't working.

    chrome.tabs.onCreated.addListener(doStuff);
  }
});

  // Functions

  // Potential function to removeListener. Not working.
  function doStuff(tab){
    chrome.tabs.onCreated.removeListener(doStuff);
  }

  var runExtension = function(){
    chrome.tabs.onCreated.addListener(function(tab){

      // Find and set reference to the current window
      chrome.windows.getCurrent(function(window){
        currentWindow = window;
      });

      // Logic to limit tabs (remove window, create bookmarks, play audio, manipulate DOM on new window)
      chrome.tabs.getAllInWindow(function(tabs) {
        tabUrls = lengthRequirement(tabs);

        console.log(tabUrls);

        if (typeof tabUrls != "string") {

          createBookmarkFolder(tabUrls);
          chrome.windows.remove(currentWindow.id);
          playAudioClip();
          chrome.windows.create({ "url": "http://www.justinstewart.info/"});  
          chrome.tabs.executeScript({file: "content_script.js"});

        }
      });
    });
  }

  var playAudioClip = function(){
    var audio = new Audio("audio_file.mp3");
    audio.play();
  }

  var createBookmarkFolder = function(tabUrls){
    chrome.bookmarks.create(
      {'title': "Caroline Strikes Again @ " + new Date()},
      function(bookmark){
        createBookmarks(tabUrls, bookmark);
      }
    )
  }

  var createBookmarks = function(urls, folder){
    for(i=0; i<urls.length; i++) {
      chrome.bookmarks.create({
        'parentId': folder.id,
        'url': urls[i][0],
        'title': urls[i][1]
      })
    }
  }

  var lengthRequirement = function(tabsArray){
    if (tabsArray.length > 9) {
      var urls = [];

      for(i=0; i<tabsArray.length; i++) {
        info = [];
        info.push(tabsArray[i].url);
        info.push(tabsArray[i].title);

        urls.push(info);
      }
      return urls;
    } else {
      return "Not there yet.....";
    }
  }

+++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++

manifest.json档案:

{
  "manifest_version": 2,
  "name": "Caroline",
  "version": "0.2",

  "description": "A fun tab limiter to help increase productivity and focus.",

  "icons": { 
    "16": "icon16.png",
    "48": "icon48.png",
    "128": "icon128.png" 
  },

  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },

  "browser_action": {
    "default_icon": "icon48.png",
    "default_title": "Sweet Caroline" 
  },

  "permissions": [
    "tabs", "bookmarks", "*://*/"
  ]
}

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:5)

.removeListener(func)仅在func与之前添加的事件侦听器之一相同时才会删除侦听器。

首先,删除runExtension中的匿名函数,因为如果它是匿名的,则无法再获得对函数对象的引用:

var runExtension = function(){
    chrome.tabs.onCreated.addListener(function(tab){
    ...
    });
};

然后,将runExtension()替换为.addListener(runExtension);,并在需要删除侦听器时使用.removeListener(runExtension);

chrome.browserAction.onClicked.addListener(function(tab){
    toggle = !toggle;
    if (toggle) {
        ...
        chrome.tabs.onCreated.addListener(runExtension);
    } else {
        ...
        chrome.tabs.onCreated.removeListener(runExtension);
    }
});