OEH
OEH

Reputation: 705

How to trigger offline background function when my PWA is closed

Based on this answer: Using setInterval in Service worker from three years ago,

I would like to know if is there any way to make a PWA (via service worker or not) to trigger some background function time based and not network related.

I would like to push a notification using the navigator built in notification Chrome API every minute when my PWA is closed.

I see service workers main goals is to cache resources, but in every documentation I see that they are in some way "always active", so I feel one of those event listeners available should do what I am amaing to.

Upvotes: 5

Views: 5175

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56164

Silently restarting your registered service worker every minute while your PWA is closed is something that browsers actively prevent. This would be a vector for malicious behavior in a lot of scenarios.

That being said, there are two options for starting up your registered service worker either not silently, or less frequently.

Push Notifications

On the "not silently" side of things, you could use push notifications to start up your service worker based on an incoming message sent from a push notification server. Users need to opt-in to receiving push notifications first. You're required to show a user-visible notification inside your service worker's push event handler, so this method isn't "silent."

You need to trigger these push events via a remote server. You can't "wake up" a service worker via push events coming from a local device.

Periodic Background Sync

Periodic background sync is a newer feature that is closer to what you describe. It allows web apps that have met certain conditions to register for a periodicsync event that will be fired automatically (without requiring a remove server) on a recurring basis. You do not need to show a user-visible notification inside of this periodicsync event handler.

The specific limitations that apply to periodic background sync are browser-dependent, but at least in Chrome, you can't register for periodicsync events that are triggered anywhere nearly as frequently as once a minute. One event a day, if the other conditions are met, is about as often as you should expect.

Upvotes: 6

Related Questions