增加服务工作线程的生命周期

increase Service Worker life time

本文关键字:生命 周期 线程 服务工作 增加      更新时间:2023-09-26

我正在尝试使用服务工作者推送通知。使用我自己的服务器发送通知,事件源用于建立连接。打开网页后,服务工作者运行良好。但它在几秒钟后停止。我想要的是运行服务工作者而不会停止。我希望它运行直到打开浏览器。任何人都可以推荐一种方法来做到这一点。?

这是我的服务工作者 JS

/**
 * 
 */
'use strict';
var eventSource2 = new EventSource("Servlet");
console.log('Started', eventSource2);
eventSource2.addEventListener('install', function(event) {
    eventSource2.skipWaiting();
    console.log('Installed', event);
});
eventSource2.addEventListener('push',function(event) {
                    console.log(event.data);
                    var title = event.data;
                    self.registration.showNotification(title,{
                                        'body' : event.data,
                                        'icon' : 'http://icons.iconarchive.com/icons/designbolts/free-multimedia/1024/iMac-icon.png',
                                        'tag' : 'click',
                                    });
                    console.log("data from down", event.data);
                });
eventSource2.addEventListener('activate', function(event){
    console.log('Activated', event);
});
eventSource2.addEventListener('fetch', function(event) {
    console.log('Push message', event);
});

服务人员的寿命很短,你不能让他们永远运行。

您可以使用共享辅助角色来执行此操作,但它们仅在您的网站打开时运行。

您正在尝试混合推送 API 和事件源。如果使用推送 API,则无需始终保持服务工作线程处于活动状态,只需在推送通知到达时使其执行即可。

请参阅 ServiceWorker Cookbook 上的示例。

当你像这里这样推送时:

self.addEventListener('push',function(event) {

首先要做的是使用 event.waitUntil() 谁接受承诺并延长事件和服务工作者的生存期

self.addEventListener('push',function(event) {
  event.waitUntil(<YOUR PROMISE>)
}

这是不可能的,也不是服务工作者的目的。你到底为什么要让它活着?