Remove HTML5 notification permissions

后端 未结 2 913
孤街浪徒
孤街浪徒 2021-01-11 15:45

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

Notification.requestPermission(callback);

But is

2条回答
  •  悲哀的现实
    2021-01-11 16:28

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

    
    

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

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

    You could retrieve the permissions as:

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

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

    if (getNotificationPermissions() === 'granted') {
        new Notification(/*...*/);
    }
    

提交回复
热议问题