在实现 chrome 推送通知时,我们从服务器获取最新更改。执行此操作时,服务工作人员会显示一 strip 有消息的额外通知
This site has been updated in the background
已经尝试过此处发布的建议
https://disqus.com/home/discussion/html5rocks/push_notifications_on_the_open_web/
但到目前为止找不到任何有用的东西。有什么建议吗?
最佳答案
简短回答:您应该使用 event.waitUntil
并向其传递一个 promise ,最终返回
showNotification
。 (如果您有任何其他嵌套的 Promise,您也应该返回它们。)
我遇到了同样的问题,但经过长时间的研究,我发现这是因为 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
})
});
})
);
});
最小场景:
self.addEventListener('push', event => {
const data = event.data.json();
event.waitUntil(
// in here we pass showNotification, but if you pass a promise, like fetch,
// then you should return showNotification inside of it. like above example.
self.registration.showNotification(data.title, {
body: data.content
})
);
});
关于google-chrome - Chrome推送通知: This site has been updated in the background,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31108699/