这种情况经常发生的原因是返回给event.waitUntil() 的承诺没有解决并显示通知。
可能显示默认推送通知的示例:
function handlePush() {
// BAD: The fetch's promise isn't returned
fetch('/some/api')
.then(function(response) {
return response.json();
})
.then(function(data) {
// BAD: the showNotification promise isn't returned
showNotification(data.title, {body: data.body});
});
}
self.addEventListener(function(event) {
event.waitUntil(handlePush());
});
你可以这样写:
function handlePush() {
// GOOD
return fetch('/some/api')
.then(function(response) {
return response.json();
})
.then(function(data) {
// GOOD
return showNotification(data.title, {body: data.body});
});
}
self.addEventListener(function(event) {
const myNotificationPromise = handlePush();
event.waitUntil(myNotificationPromise);
});
这很重要的原因是浏览器等待传递给 event.waitUntil 的承诺来解决/完成,以便他们知道服务工作者需要保持活跃和运行。
当 Promise 解决了推送事件时,Chrome 将检查通知是否已显示,并且它是否属于 Chrome 是否显示此通知的竞争条件/特定情况。最好的办法是确保你有一个正确的承诺链。
我在这篇文章中添加了一些关于承诺的额外注释(参见:'Side Quest: Promises'https://gauntface.com/blog/2016/05/01/push-debugging-analytics)