Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove HTML5 notification permissions

You can prompt a user to allow or deny desktop notifications from the browser by running:

Notification.requestPermission(callback);

But is it possible to remove that permission by code? We want our users to have the option to toggle notifications. Can this be achieved by JavaScript or do we need to save that option elsewhere?

like image 829
Hans Westman Avatar asked Feb 12 '15 13:02

Hans Westman


People also ask

Why is a website sending me notifications?

By default, Chrome alerts you whenever a website, app, or extension wants to send you notifications. You can change this setting at any time. When you browse sites with intrusive or misleading notifications, Chrome automatically blocks notifications and recommends you continue to block these notifications.

How do I stop website push notifications?

On Android, head to Settings > Site Settings > Notifications to control your device's notifications.


1 Answers

Looking at the documentation on Notification at MDN and WHATWG, there does not seem to be a way to request revocation of permission. However, you could emulate your own version of the permission using localStorage to support that missing functionality. Say you have a checkbox that toggles notifications.

<input type="checkbox" onChange="toggleNotificationPermission(this);" />

You can store your remembered permissions under the notification-permission key in local storage, and update the permission state similar to:

function toggleNotificationPermission(input) {
    if (Notification.permission === 'granted') {
        localStorage.setItem('notification-permission', input.checked ? 'granted' : 'denied');
    } else if (Notification.permission === 'denied') {
        localStorage.setItem('notification-permission', 'denied');
        input.checked = false;
    } else if (Notification.permission === 'default') {
        Notification.requestPermission(function(choice) {
            if (choice === 'granted') {
                localStorage.setItem('notification-permission', input.checked ? 'granted' : 'denied');
            } else {
                localStorage.setItem('notification-permission', 'denied');
                input.checked = false;
            }
        });
    }
}

You could retrieve the permission as:

function getNotificationPermission() {
    if (Notification.permission === 'granted') {
        return localStorage.getItem('notification-permission');
    } else {
        return Notification.permission;
    }
}

When you want to display a notification, check your permission:

if (getNotificationPermission() === 'granted') {
    new Notification(/*...*/);
}
like image 139
Uyghur Lives Matter Avatar answered Oct 10 '22 16:10

Uyghur Lives Matter