Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove event listener in Chrome extension

Tags:

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!

like image 857
chaohuang Avatar asked May 05 '12 22:05

chaohuang


People also ask

How do I delete an event listener?

Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.


2 Answers

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);     } ); 
like image 161
apsillers Avatar answered Sep 20 '22 11:09

apsillers


Another simple and straight forward approach when using anonymous functions:

chrome.runtime.onMessage.addListener(function(msg, sender, reply) {     chrome.runtime.onMessage.removeListener(arguments.callee); }); 
like image 20
Prakash GPz Avatar answered Sep 19 '22 11:09

Prakash GPz