在实施Chrome推送通知时,我们从服务器获取最新更改。在这样做时,服务工作者正在显示带有消息的额外通知
此网站已在后台更新
已经尝试过此处发布的建议
https://disqus.com/home/discussion/html5rocks/push_notifications_on_the_open_web/
但到目前为止找不到任何有用的东西。有什么建议吗?
答案 0 :(得分:23)
我遇到了同样的问题,但经过长时间的研究后我才知道这是因为PUSH事件和self.registration.showNotification()之间发生了延迟。我在self.registration.showNotification()
之前只错过了return关键字因此,您需要实现以下代码结构以获取通知:
var APILINK = "https://xxxx.com";
self.addEventListener('push', function(event) {
event.waitUntil(
fetch(APILINK).then(function(response) {
return response.json().then(function(data) {
console.log(data);
var title = data.title;
var body = data.message;
var icon = data.image;
var tag = 'temp-tag';
var urlOpen = data.URL;
return self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag
})
});
})
);
});
答案 1 :(得分:12)
通常,只要您收到来自GCM(Google Cloud Messaging)的推送消息,您就必须在浏览器中显示推送通知。这在第3点提到:
所以可能会发生以某种方式你正在跳过推送通知,虽然你收到了来自GCM的推送消息,并且你正在获得推送通知,其中包含一些默认消息,例如"此网站已在后台更新"
答案 2 :(得分:12)
我过去遇到过这个问题。根据我的经验,原因通常是三个问题之一:
userVisibleOnly:
true
选项(虽然注意这不是可选的,而不是设置它
将导致订阅失败。event.waitUntil()
。应该将一个承诺传递给此函数,以向浏览器指示它应该等待承诺解析,然后再检查是否显示通知。event.waitUntil
的承诺。请注意,self.registration.showNotification
是一个承诺和异步,所以在传递给event.waitUntil
的承诺结算之前,您应该确定它已经解决。答案 3 :(得分:2)
我试图理解为什么Chrome要求服务人员在收到推送通知时必须显示通知。我认为原因是,即使用户关闭了网站的选项卡,推送通知服务工作人员仍继续在后台运行。因此,为了防止网站在后台秘密运行代码,Chrome要求它们显示一些消息。
What are the limitations of push messaging in Chrome?
...
- 您必须在收到推送消息时显示通知。
...
和
Why not use Web Sockets or Server-Sent Events (EventSource)?
使用推送消息的优势在于,即使您的页面关闭,您的服务人员也会被唤醒并能够显示通知。关闭页面或浏览器时,Web套接字和EventSource的连接也将关闭。
答案 4 :(得分:1)
这很有效,只需复制/粘贴/修改即可。替换"返回self.registration.showNotification()"使用以下代码。第一部分是处理通知,第二部分是处理通知的点击。但不要感谢我,除非你感谢我用谷歌搜索答案的时间。
说真的,非常感谢Matt Gaunt在developers.google.com
self.addEventListener('push', function(event) {
console.log('Received a push message', event);
var title = 'Yay a message.';
var body = 'We have received a push message.';
var icon = 'YOUR_ICON';
var tag = 'simple-push-demo-notification-tag';
var data = {
doge: {
wow: 'such amaze notification data'
}
};
event.waitUntil(
self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag,
data: data
})
);
});
self.addEventListener('notificationclick', function(event) {
var doge = event.notification.data.doge;
console.log(doge.wow);
});
答案 5 :(得分:1)
如果在收到推送通知事件时需要进行更多操作,则showNotification()
将返回Promise
。因此,您可以使用经典链接。
const itsGonnaBeLegendary = new Promise((resolve, reject) => {
self.registration.showNotification(title, options)
.then(() => {
console.log("other stuff to do");
resolve();
});
});
event.waitUntil(itsGonnaBeLegendary);