增加服务人员的生活时间 [英] increase Service Worker life time

查看:101
本文介绍了增加服务人员的生活时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying push notifications using service workers. use my own server to send notifications and eventSource is used to establish the connection. after i open the webpage service worker is running perfectly. but it stops after few seconds. what i want is to run service worker without getting stopped. i want it to run until the browser is opened. can anyone recommend a way to do that. ?

这是我的ServiceWorker JS

this is my ServiceWorker 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);
});


推荐答案

服务工作者的生命周期短,你无法让它们永远运行。

Service workers are meant to have a short lifetime, you can't make them run forever.

您可以使用共享工作人员来执行此操作,但只有在您的网站处于打开状态时才会运行。

You could use a shared worker to do that, but they only run if your website is open.

您正在尝试混合推送API和EventSource。如果您使用Push API,则无需始终使服务工作者保持活动状态,只需在推送通知到达时执行即可。

You are trying to mix the push API and EventSource. If you use the Push API, you don't need to keep the service worker alive all the time, you can just make it execute when a push notification arrives.

请参阅 ServiceWorker Cookbook上的示例

这篇关于增加服务人员的生活时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆