chaohuang
chaohuang

Reputation: 4115

How to remove event listener in Chrome extension

I am trying to remove the onRequest listener added by chrome.extension.onRequest.addListener after a request is made, like this:

chrome.extension.onRequest.addListener(
    function(request){
        chrome.extension.onRequest.removeListener();
        other_function(request);
    }
);

The problem is that I don't know if this works or not. I tried chrome.extension.onRequest.hasListener, which seems not to give the right answer, so I am wondering if there are some other ways to remove the onRequest listener or check if the listener exists or not.

Thanks!

Upvotes: 32

Views: 32774

Answers (3)

Kristiyan Tsvetanov
Kristiyan Tsvetanov

Reputation: 1047

// define listener(s)
const createListener = (id, bookmark) => {
  // do something
};

React.useEffect(() => { 
  // Add listener(s)
  chrome.bookmarks.onCreated.addListener(createListener);

  // Return a function that removes listener(s)
  return () => {
    chrome.bookmarks.onCreated.removeListener(createListener);
  };
}, []);

Upvotes: 1

Prakash GPz
Prakash GPz

Reputation: 1523

Another simple and straight forward approach when using anonymous functions:

chrome.runtime.onMessage.addListener(function(msg, sender, reply) {
    chrome.runtime.onMessage.removeListener(arguments.callee);
});

Upvotes: 11

apsillers
apsillers

Reputation: 116050

removeListener takes an argument. You need to name the listener function and then remove it by name:

function doStuff(request){
    chrome.extension.onRequest.removeListener(doStuff);
    other_function(request);
}
chrome.extension.onRequest.addListener(doStuff);

Or, more succinctly:

chrome.extension.onRequest.addListener(
    function doStuff(request){
        chrome.extension.onRequest.removeListener(doStuff);
        other_function(request);
    }
);

Upvotes: 60

Related Questions