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)
})
}
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 filejs
and the Service Worker– Lauro Moraes