Search code examples
mozillaweb-push

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.


Solution

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