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