Jay
Jay

Reputation: 503

Trouble removing event listener

Trying to get my feet wet with Chrome Extensions. 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. 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.

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.

Here is the 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_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!

Upvotes: 2

Views: 1153

Answers (1)

Rob W
Rob W

Reputation: 349222

.removeListener(func) will only remove a listener if func is identical to one of the previously added event listeners.

First, remove the anonymous function within runExtension, because if it is anonymous, you cannot get a reference to the function object any more:

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

Then, replace runExtension() with .addListener(runExtension);, and use .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);
    }
});

Upvotes: 5

Related Questions