gpt4 book ai didi

Javascript Service worker onload 显示通知

转载 作者:搜寻专家 更新时间:2023-11-01 04:35:47 25 4
gpt4 key购买 nike

我有一个已注册的服务 worker ,但我想循环一个函数来检查服务器上的更新并显示通知,即使在选项卡关闭时也是如此。

在 serviceworker.js 中使用以下代码,我得到一个错误;“未捕获( promise )TypeError:ServiceWorkerRegistration 上没有可用的事件注册。”

self.registration.showNotification(title, {
body: 'We have received a push message',
icon: '',
tag: ''
})

我希望在打开浏览器时弹出通知,就像 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
})
);
});

Refer google's getting started with web-push-notifications for detailed understanding.

关于Javascript Service worker onload 显示通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35364235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com