简体   繁体   English

无法删除事件侦听器

[英]Trouble removing event listener

Trying to get my feet wet with Chrome Extensions.试图用 Chrome 扩展程序弄湿我的脚。 I created a tab limiter, but its buggy.我创建了一个制表符限制器,但它有问题。

I want the event of clicking the browser action icon to toggle on and off the extension.我希望单击browser action图标的事件可以打开和关闭扩展程序。 I believe I have that set up properly.我相信我已经正确设置了。 When toggled on, it creates a listener from the chrome.tabs API, but when toggled off, I'm having a hard time removing this listener.打开时,它会从chrome.tabs API 创建一个侦听器,但是当关闭时,我很难删除这个侦听器。

I've tried some of the common answers on Stack Overflow (one is shown below) for removing listeners, but none are functioning properly for me.我已经尝试了 Stack Overflow 上的一些常见答案(如下所示)来删除侦听器,但没有一个对我来说正常工作。

Here is the background.js这是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 file: 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", "*://*/"
  ]
}

Any help is greatly appreciated!任何帮助是极大的赞赏!

.removeListener(func) will only remove a listener if func is identical to one of the previously added event listeners.如果func与之前添加的事件侦听器之一相同,则.removeListener(func)只会删除侦听器。

First, remove the anonymous function within runExtension , because if it is anonymous, you cannot get a reference to the function object any more:首先,删除runExtension中的匿名函数,因为如果它是匿名的,您将无法再获得对函数对象的引用:

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

Then, replace runExtension() with .addListener(runExtension);然后,将runExtension()替换为.addListener(runExtension); , and use .removeListener(runExtension); , 并使用.removeListener(runExtension); whenever you want to remove the listener:每当您想删除侦听器时:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM