删除 HTML5 通知权限

Remove HTML5 notification permissions

您可以提示用户允许或拒绝来自浏览器的桌面通知,方法是 运行:

Notification.requestPermission(callback);

但是是否可以通过代码删除该权限?我们希望我们的用户可以选择切换通知。这可以通过 JavaScript 实现,还是我们需要将该选项保存在其他地方?

不,您的脚本无法以编程方式放弃显示通知的权限。 API specification除了requestPermission外没有任何权限相关的功能。 (当然,浏览器可能有一个允许用户撤销域权限的选项菜单,但那是浏览器级别的选项,而不是站点级别的选项。例如,在 Chrome 中,您可以看到单击地址栏左侧的图标即可打开此选项菜单。)

如果您不想显示通知,只需不要调用new Notification

您可以将所有调用包装到 new Notification 内部条件:

if(notifications_allowed) {
    new Notification(...);
}

或者您可以重写 Notification 构造函数以包含条件并适当地调用原始 Notification

(function() {
    var oldNofitication = Notification;
    Notification = function() {
        if(notifications_allowed) {
            oldNotification.apply(this, arguments);
        }
    }
})();

如果您使用供应商前缀的构造函数或函数(例如,webkitNotifications.createNotification),那么您将需要重写每一个,并以您的选项变量为条件。

查看 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 上的文档以支持缺少的功能。假设您有一个用于切换通知的复选框。

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

您可以将您记住的权限存储在本地存储中的 notification-permission 密钥下,并更新权限状态类似于:

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;
            }
        });
    }
}

您可以检索权限为:

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

当您想要显示通知时,请检查您的权限:

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