【问题标题】:How to check if notifications is already allowed by user in google chrome?如何检查谷歌浏览器中的用户是否已经允许通知?
【发布时间】:2016-10-24 16:57:38
【问题描述】:

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

【问题讨论】:

    标签: javascript google-chrome push-notification notifications service-worker


    【解决方案1】:

    检查 Notification 对象的permission 属性:

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

    【讨论】:

    • 谢谢!完美运行。
    • 另外,Notification.permission !== "denied"。
    【解决方案2】:

    Denys Séguret 回答的Notification.permission 一起,还有更新、支持较少但更通用的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();
    

    【讨论】:

      猜你喜欢
      • 2021-05-27
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 2011-05-06
      • 1970-01-01
      • 2018-09-21
      • 2016-03-31
      相关资源
      最近更新 更多