[英]Receive notifications 24/7 via service-worker.js in Chrome
我一直在进行推送通知,当我注册页面然后通过curl命令对其进行测试时,我收到了通知!
但是,过了一会儿(也许是1-2分钟),当我关闭选项卡,通知推送作用域已被注册,然后再次测试通知时,我无法收到通知。 这种情况通常发生在移动设备的Google Chrome浏览器中。
我在这里所做的解决方法是,我需要先转到作用域页面的页面,然后当我再次测试通知时,它现在可以工作了。 尽管我无法做到这一点,因为我需要客户端来接收通知,而不必一直在网站上。
这是我在服务人员中的推送活动
self.addEventListener('push', function(event) {
var SOME_API_ENDPOINT = "https://somewhre.com/push_notification_api/service_worker_endpoint";
event.waitUntil(
fetch(SOME_API_ENDPOINT, {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'subscription_id=' + subscriptionId
}).then(function(response) {
return response.json().then(function(data) {
var title = data.notification.title;
var message = data.notification.message;
var icon = base + "assets/images/logo_notification.png";
var notificationTag = data.notification.url;
// var notificationTag = 'https://google.com'; //data.notification.tag;
return self.registration.showNotification(title, {
body: message,
icon: icon,
tag: notificationTag
});
});
})
);
});
即使我不在SW的注册范围之内,如何使我的服务人员成为24/7全天候服务?
我是否需要使用eventListeners的“安装”,“激活”和“获取”?
服务人员似乎坚持不懈,但实际上并非如此-响应事件,一个新实例启动了。 在移动设备上重新启动以处理推送事件时将是这种情况,但也有人建议繁忙的服务工作者应允许并行运行多个实例。
您的subscriptionId
是一个全局参数,因此在您的push
事件触发时很可能undefined
。
要解决此问题,您需要将subscriptionId
保留在某种类型的存储中(Mayber IndexedDB)。
我还认为,为了使服务人员能够持久运行,它需要有一个install
事件,并且该事件需要成功。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.