如何检查 google chrome 中的用户是否已允许通知?

How to check if notifications is already allowed by user in google chrome?

我有一个模式,首先弹出询问用户是否想要接收特别优惠,如果他们点击是,然后我拉入推送通知的代码,以便他们可以允许通知。如果他们已经允许通知,我不希望弹出模式。我正在寻找一种方法来检查用户是否已经允许通知,使用 google chrome.

检查通知对象的permission 属性:

if (Notification.permission !== "granted") {
    // ask for permission

Notification.permission 一起,由 there is the newer, less well-supported but more general Permissions API.

回答

这是一个快速使用示例,基于 the one from MDN:

function handlePermission() {
    return navigator.permissions
            .query({name:'notifications'})
            .then(permissionQuery)
            .catch(permissionError);
}

function permissionQuery(result) {
    console.debug({result});
    var newPrompt;

    if (result.state == 'granted') {
        // notifications allowed, go wild

    } else if (result.state == 'prompt') {
        // we can ask the user
        newPrompt = Notification.requestPermission();

    } else if (result.state == 'denied') {
        // notifications were disabled
    }

    result.onchange = () => console.debug({updatedPermission: result});

    return newPrompt || result;
}

////

handlePermission();