有什么方法可以使用javascript显示本机窗口或桌面通知?

时间:2019-03-13 13:47:03

标签: javascript html5 google-chrome notifications

我试图获得在Chrome和Brave上运行的通知,但是当我单击按钮时什么也没有显示。它确实会在第一次请求许可,如果我使用console.log刷新,它会显示“已授予”。因此,应该可以使用new Notification();构造函数创建一个新的通知。问题在于它什么也没显示。

我已经检查了网页的设置,并且一切正常。我感觉Chrome的支持不再适用于Notifications API。有没有更好的方法来使用Javascript来获取通知,因此,如果满足一定的数据要求,它将向所有用户/访问者显示通知?

此外,即使关闭页面也如何显示通知?

代码

<div class="container">
    <h1>Notification Test</h1>
    <button onclick="notifyMe()">I want a notification!</button>
</div>

<script>
function notifyMe(){
    // Let's check if the browser supports notifications
    if (!("Notification" in window)) {
        alert("This browser does not support desktop notification");
    }

    // Let's check if the user is okay to get some notification
    else if (Notification.permission === "granted") {
        // If it's okay let's create a notification
        var notification = new Notification("Hi there!");
        notification.show();
    }

    // Otherwise, we need to ask the user for permission
    // Note, Chrome does not implement the permission static property
    // So we have to check for NOT 'denied' instead of 'default'
    else if (Notification.permission !== 'denied') {
        Notification.requestPermission(function (permission) {

            // Whatever the user answers, we make sure we store the information
            if(!('permission' in Notification)) {
                Notification.permission = permission;
            }

            // If the user is okay, let's create a notification
            if (permission === "granted") {
                var notification = new Notification("Hi there!");
            }
        });
    }
}
</script>

0 个答案:

没有答案