Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

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(/*...*/);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...