【问题标题】:How to add a push notification to a website?如何向网站添加推送通知?
【发布时间】:2018-04-17 13:53:12
【问题描述】:

我正在尝试向我的网站添加推送通知。当用户登录时,他们将收到一条通知,提醒他们添加结果。我在 chrome 弹出窗口中找到了代码,但它似乎不起作用。

<script>
Notification.requestPermission(function(status) {
    console.log('Notification permission status:', status);
});

function displayNotification() {
 if(Notification.permission=="granted"){
                    jQuery('#notification-head').hide();
                    notify=new Notification("New Blog Available",{
                    body:"Demo paragraph",
                    icon:'bg-Img.png',
                    tag:'12222'
                    });
                    notify.onclick=function(){
                    notify.close();
    }  
}
</script>

【问题讨论】:

  • 好吧,至少你的 displayNotification 函数中缺少结尾 }
  • @Rantanen,我认为它更像是桌面通知,而不是那样的弹出警报。
  • @entiendoNull 谢谢我添加了一个额外的 } 但它只询问我是否允许通知,它实际上并没有显示!
  • 您在检查是否已获得许可之前请求许可。
  • 只需将您的代码替换为 mdn 上的示例...developer.mozilla.org/en-US/docs/Web/API/Notifications_API/…

标签: javascript php html push-notification


【解决方案1】:

您需要在函数末尾添加一个花括号。你可以看看this example。另外,你永远不会调用displayNotification,你需要使用这个:

Notification.requestPermission(function(status) {
  console.log('Notification permission status:', status);
  displayNotification();
});

function displayNotification() {
    if(Notification.permission == "granted"){
    $('#notification-head').hide();
    let notify = new Notification("New Blog Available", {
        body:"Demo paragraph",
        icon:'bg-Img.png',
        tag:'12222'
    });
    notify.onclick = function(){
     notify.close();
    }  
    }
}

【讨论】:

  • 您在检查是否已获得许可之前请求许可。
  • 那又怎样?如果它已经被授予它不会有所作为。
  • 对不起,我的错误。我做了一个小的编辑,以便能够删除它
  • 好的,没问题。
猜你喜欢
  • 1970-01-01
  • 2020-12-17
  • 1970-01-01
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
相关资源
最近更新 更多