Execute js Service Worker function even with the browser closed or minimized

0

Recently I'm using Service Worker, I came to see some examples and the documentation that has google labs, but I confess that I'm having a hard time understanding how I can create a function in Service Worker, which should be executed every time 3 minutes even if the user close the browser or if he just minimize it . Thank you in advance if you can give me some guidance.

My current scenario:
- Framework Php Laravel 5.5,
- php 7.0,
- jquery,
- Postgresql,
- bootstrap,
- HTTPS server
- I have already been able to install the service worker service in the browser, the scope of it I configured to get everything that is inside the root of the site. The sw.js file is located inside the public folder of Laravel.

    
asked by anonymous 06.04.2018 / 04:20

1 answer

1

Service Worker is a proxy, it performs functions during the request and then terminates.

The Web-Push and Sync APIs can operate on background even though the user is not in the bad application, the browser is "open" even minimized.

You can use PostMessage with an interval (function) logic to post messages between your js and Service Worker files:

sw.js :

function ExecutaFuncao() {
    postMessage({
        cmd: 'response',
        data: 'um valor qualquer'
    })
}
// message handler
self.addEventListener('message', event => {
    if ( 'cmd' in event.data ) {
        let command = event.data.cmd
        switch (command) {
            case 'executa-funcao':
                ExecutaFuncao()
            break
        }
    }
})
// enviar mensagem do Service Worker
async function postMessage(data) {
    let clients = await self.clients.matchAll()
    clients.forEach(client => client.postMessage(data))
}

You can send parameters to functions defined in your Service Worker ... or simply perform functions depending on the "command" you send.

main.js

if ( 'serviceWorker' in navigator ) {
    // observe messages
    navigator.serviceWorker.addEventListener('message', event => {
        if ( 'cmd' in event.data ) {
            let command = event.data.cmd
            switch(command) {
                case 'response':
                    console.log('[ServiceWorker Response]: ', event.data.data)
                break
            }
        }
    })
    // simple lógic
    setInterval(() => {
        if ( navigator.serviceWorker.controller ) {
            navigator.serviceWorker.controller.postMessage({
                cmd: 'executa-funcao'
            })
        }
     }, 5000) // every 5 seconds

    // register
    navigator.serviceWorker.register('/sw.js', {
        scope: '/'
    }).then(register => {
        console.log('[Register ServiceWorker] We are live                                     
06.04.2018 / 04:58