The notification prompt can only be triggered by a user gesture on some browsers

On some browsers, the permission prompt for notifications can be displayed only after a user interaction with the website. Let’s see why some browsers enforce this rule, what happens if you don’t comply with it and how can you implement a solution that works across all major browsers.

The problem

In order to send notifications to a user from a website, you need to request the user permission. As many websites do, you may think that the best solution is to ask the user to subscribe to notifications as soon as they enter your website. This behavior is considered a bad practice from some usability guides and an annoyance for the users: for this reason some browsers have decided to block the permission prompt if you display it on page load.

Basically you need to wait that the user clicks a button or something similar and then display the permission prompt (inside the user-generated event).

If you don’t comply with this rule, the browser will simply return an error and the prompt will not be displayed.

In particular, you will get this error on Safari:

Push notification prompting can only be done from a user gesture.

And you get this error on Firefox:

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

Note that currently Chrome allows you to display the permission prompt on page load, so you won’t get any error on Chrome.

The solution

The solution to this problem is to wait for a user gesture (e.g. a click on a button) and then display the permission prompt from that event.

For example if you use Pushpad:

document.querySelector('#my-button').addEventListener('click', function() {
  pushpad('subscribe'); // call PushManager.subscribe() and display the prompt
});

Another alternative, if you want to display a prompt as soon as the users land on your website, is to use a double opt-in for notifications. Basically you can display a prompt designed using HTML and CSS when the user arrives on your website, then you display the actual permission prompt when the user clicks Subscribe on the first prompt. In this way the permission prompt is still triggered from a user-generated event and you can also give useful information to the user in the first prompt.

Leave a Reply

Your email address will not be published. Required fields are marked *