javascriptpush-notificationservice-workerprogressive-web-appsofflineapps

Call a function every minute from a service worker for an offline PWA


I'm working on a Progressive Web App (PWA) with offline support and I need to call a function in the app every minute from the service worker. (to send a web API based push notification if the user is offline)

What is the best way to do this?


Solution

  • to call the function every minute use setInterval():

    function myFunction(){
    	console.log('called evry minute')
    }
    
    setInterval(myFunction, 1000);

    But you can listen for online and offline events to send the notifications accordingly , see compatibility of NavigatorOnLine , as it won't work in Opera

    window.addEventListener('online',  functionWhenOnline);
    window.addEventListener('offline', functionWhenOffline);