Run js Service Worker function even with browser closed or minimized

Asked

Viewed 179 times

0

Recently I’m using Service Worker, I came to consult some examples and the documentation you have on google Labs, but I confess that I’m having difficulties to understand how I can create a function in the Service Worker , which should be run every 3 minutes even if the user closes the browser or if it just minimizes it. Thanks 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 have set up to get everything inside the root of the site. The archive sw.js is located inside the public folder of Laravel.

  • Service Worker is a Proxy, it performs functions during the request and then terminates. Web-Push and Sync Apis can operate on "background" even if the user is not in the bad application, it is necessary that the browser is "open" even minimized. You can use PostMessage with a logic (function) of ranges to send messages between your file js and the Service Worker

1 answer

1


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

The Apis Web-Push and Sync can operate in "background" even if the user is not in the bad application, it is necessary that the browser is "open" even minimized.

You can use PostMessage with a logic (function) of ranges to send messages between your file js and the Service Worker:

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" sent.

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  !')
    }).catch(e => {
        console.warn('service worker failed', e)
    })
}
  • 1

    Cool @Lauromoraes, I’ve got an idea of where I should go now. I appreciate the help. How does it work here on the forum, just click on your answer as the chosen answer? Sorry, it’s my first participation here rsrs.

  • Yes, that’s how it works. Just click on the icon , If another answer appears that you judge to be "better" within the scope of your question it will be enough to change the answer choice accepted without problems. Welcome to the community/

  • Thank you very much @Lauromoraes. I hope I can help others as well, just as I am being helped. A hug.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.