How to use funtions of notifications.onClicked event?

From this article on MDN:

The notifications.onClicked has 3 functions which is:


I can understand addListener(callback) pretty well, but removeListener(listener) and hasListener(listener) is kinda annoying to me. I totally have no idea what actually are. So here is some questions keep wondering in my mind:

  1. What is listener? Is it a promise object or id string of a notification?
  2. Where do we get it (the listener)? It cannot a vague callback function right?
  3. How to use these functions? The idea of remove functions is hard to understand to me? Why would we need to remove it? A thing that we try so hard to add it to an event? Moreover, isn’t it will be get rid of event after the object destroyed? Notifications don’t last forever right. And if we really need to change the content of notification, we can just use browser.notifications.update().

I’ve checked Chrome document but it doesn’t seem they have these functions.

listener is a function. A function listening to the event. You make that function yourself.

The idea of has and remove is that you pass the same function that you passed to add listener if you want to do these actions. You will not have to manage your listeners with remove/has listeners in most situations. It behaves pretty much the same as on the web. You need these methods if you want to explicitly stop receiving events, or find out if something is receiving events.

1 Like

But how do has and remove know that the function we pass to is the same function we used for add? I don’t think it could see functions as object because there are some returned functions as well.

If you pass the same function reference, it can compare the function references. So to use these methods, it’s important to pass a function reference and not a function literal (which is a reference too, just that you don’t store the reference).

1 Like

I think I not fully get it well. I still have some trouble in understanding the ‘function references’. So, I hope you don’t mind if I ask for a simple example of function references? I’m sorry, but I’m just an amateur who start from HTML to JS and struggling with C++ at pointers so…

Whenever you pass a function as parameter, the function is not copied. So I can do this:

const myFunction = () => console.log('foo');
const myOtherFunction = () => console.log('bar');
const isMyFunction = (fun) => fun === myFunction;

console.log(isMyFunction(() => console.log('foo')));

and it will log


This of course applies to all styles of writing a function.

1 Like