Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notification.requestPermission() throwing error on Mozilla

I' m trying to get notification for Mozilla. But it continuously throwing this error.

The Notification permission may only be requested from inside a short running user-generated event handler.

Here is my code. The same code is working fine on Chrome, EDGE and Opera.

Notification.requestPermission().then(function (status) {
    if (status === 'denied') {
        //
    } else if (status === 'granted') {
        //
    }
});

I found some questions related to this, but none of those is helpful for me.

like image 989
Jaber Kibria Avatar asked Apr 28 '20 08:04

Jaber Kibria


People also ask

How do browser notifications work?

Browser notifications are simply notifications that can be sent by web applications and websites. The messages are received by the user's browser client. Browser notifications can be sent even when the particular website is not actively in use.


1 Answers

That message means that your subscription code must be called inside a user generated event, like a click.

Probably you are trying to subscribe the user on page load, but that is not possible on some browsers, like Firefox and Safari, because it is considered an annoyance for the users.

That is one of the reasons why many push services (like OneSignal, Pushpad, etc.) suggest to use a double opt-in: first you display a subscribe prompt or button designed with HTML / CSS and then, after the click on the button, you actually request the permission (your code above).

like image 75
collimarco Avatar answered Sep 19 '22 18:09

collimarco