Rel*_*elm 5 javascript notifications google-chrome push-notification service-worker
我有一个注册的服务工作者,但是我想循环使用一个功能来检查服务器上的更新并显示通知,即使关闭了选项卡也是如此。
在serviceworker.js中使用以下代码,我得到一个错误;“未捕获(承诺)TypeError:ServiceWorkerRegistration上没有可用的活动注册。”
self.registration.showNotification(title, {
body: 'We have received a push message',
icon: '',
tag: ''
})
Run Code Online (Sandbox Code Playgroud)
我希望打开浏览器时像Facebook一样弹出通知。
好吧,你首先需要了解service-worker的生命周期
// listen for a push notification from gcm, as only it can reiterate
// your push-notifications to your clients subscriber id
// put your code inside listener
self.addEventListener('push', function(event) {
console.log('Received a push message', event);
// here you can make rest calls to fetch data against the subscriber-id
// and accordingly, set data
// keep in mind that your server sends push notifications to gcm
// and then your subscribers receive them here
var title = 'title' || 'data-from-rest-call';
var body = 'body' || 'data-from-rest-call';
var icon = '/your image path' || 'data-from-rest-call';
var tag = 'tag' || 'data-from-rest-call';
// waitUntil is a callback, it triggers when the push is ready.
event.waitUntil(
//here your ready notifications get triggered
self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag
})
);
});
Run Code Online (Sandbox Code Playgroud)
详细了解请参阅 google 的web-push-notifications入门。