在实施chrome推送通知时,我们从服务器获取最新的更改。在这样做时,服务工作者正在显示带有该消息的额外通知
此网站已在后台更新
已经尝试过这里发布的建议https://disqus.com/home/discussion/html5rocks/push_notifications_on_the_open_web/ 但到目前为止找不到任何有用的东西。有什么建议吗?
通常,只要您收到来自GCM(Google Cloud Messaging)的推送消息,您就必须在浏览器中显示推送通知。这在第3点提到:
因此,虽然您从GCM获得推送消息并且您正在获得推送通知,并且您正在获得一些推送通知,例如“此站点已在后台更新”,但可能会发生这种情况。
我遇到了同样的问题但经过长时间的研究后我才知道这是因为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
})
});
})
);
});
我过去遇到过这个问题。根据我的经验,原因通常是三个问题之一:
userVisibleOnly:
true
选项(虽然注意这不是可选的,并且不设置它将导致订阅失败。event.waitUntil()
来回应处理这个事件。应该将promise传递给此函数,以向浏览器指示它应该等待承诺解析,然后再检查是否显示通知。event.waitUntil
的承诺。请注意,self.registration.showNotification
是一个promise和async,因此在传递给event.waitUntil
的promise之前,你应该确定它已经解决了。这可以,只需复制/粘贴/修改。用以下代码替换“return 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);
});
如果在接收推送通知事件时需要更多事情发生,showNotification()
将返回Promise
。所以你可以使用经典的链接。
const itsGonnaBeLegendary = new Promise((resolve, reject) => {
self.registration.showNotification(title, options)
.then(() => {
console.log("other stuff to do");
resolve();
});
});
event.waitUntil(itsGonnaBeLegendary);