Trigger notification permission with Javascript

Jonas K
2 min readFeb 18, 2022

--

You are might working on a website, where you really want users to allow notifications for the best possible user experience. It could be they deny access, but don’t worry. There is still hope, to convince them.

The 3 different states

Working with Notification API, you can receive 3 different states, telling the user's current permission status in their browser. To get the current state, run

function checkUserPermission() {
return Notification.permission
}
  • default is the status on the user's first visit. This means that notifications are not allowed, yet. What it also means is, that this is the only state, where the popup will be visible.
  • granted and the user has allowed notifications.
  • denied and the user has not allowed notifications.

What granted and denied have in common, is that they won’t show any popup. Only default will.

In the popup, there is only a button for “Allowing” access. The state will go to denied, if notifications are ignored on users second visit. Try to visit a website with notifications, and refresh the page twice. Now the suggestion for notifications is not being shown.

Sadly, it is not possible to trigger the popup, if the status is denied. If that is the case, you probably want to add something on the website, to suggest the user, to allow permission for fully user experience.

The user has to do this manually, like shown in the picture above. You can not trigger this with codes.

Like mentioned, default is the only state, where popup is being shown — but still not allowed either. This is also the only state, where the requestPermission function can be used.

function triggerNotifications() {
Notification.requestPermission();
}

Try this, and you will see an reaction in the URL.

If you run this code and the state is denied, all you will see is a warning in the console telling you this

Notifications permission has been blocked as the user has ignored the permission prompt several times. This can be reset in Page Info which can be accessed by clicking the lock icon next to the URL. See https://www.chromestatus.com/feature/6443143280984064 for more information.

I hope you find this article useful.

--

--

Jonas K
Jonas K

Written by Jonas K

Building stuff on the world wide web. Hi👋

No responses yet