19

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.

Jaber Kibria
  • 932
  • 3
  • 9
  • 29

3 Answers3

24

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).

collimarco
  • 34,231
  • 36
  • 108
  • 142
  • 1
    @JaberKibria Indeed it is what I said... you need to request permission inside the callback for a `click` or other user-triggered events – collimarco Apr 28 '20 at 10:01
9

This piece of code worked for me:

JS

if (Notification.permission === 'granted') {
    //do something
}
else if (Notification.permission === 'default') {
    $('#allow-push-notification-bar').show();
}

$('#allow-push-notification').click(function () {
    $('#allow-push-notification-bar').hide();
    Notification.requestPermission().then(function (status) {
        if (status === 'denied') {
            //do something
        } else if (status === 'granted') {
            //do something
        }
    });
});

HTML

<div id="allow-push-notification-bar" class="allow-push-notification-bar">
    <div class="content">
        <div class="text">
            Want to get notification from us?
        </div>
        <div class="buttons-more">
            <button type="button" class="ok-button button-1" id="allow-push-notification">
                Yes
            </button>
            <button type="button" class="ok-button button-1" id="close-push-notification">
                No
            </button>
        </div>
    </div>
</div>

This will open a popup after loading the webpage with 2 buttons (Yes/No). Onclick Yes, browser will ask to allow the notification.

Ayesha Aziz
  • 106
  • 1
  • 2
6

That happened to me as well. If you don't want to use buttons or other element events, you could use a higher-level document click event and request permission from there.

document.addEventListener('click', () => {
        Notification.requestPermission().then(function (status) {
        if (status === 'denied') {
            //
        } else if (status === 'granted') {
            //
        }
    });
})