Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
How a ServiceWorker can trigger a refresh/reload by a push to all subscribers?

here is the process i would like to dev :

  • A page with a serviceWorker
  • UserA and UserB accept notification from this page only

Behavior :

  • if a user modify the page, the other users are notified (already working mobile/desktop)

Now i would like that if userA modify the page :

  • If the page was already opened on UserB browser, it refresh automaticly
  • If the userB click on notification : the page is refreshed

but it seems that :

  • ServiceWorker can't call "reload"
  • a trick such a setInterval to check last update doesn't work on android chrome (certainly for bandwidth?)

so my question is :

  • is it a way to let the server push an serviceWorker event to call a reload on each subscribers even if the page is already opened on their browser ?

In other word : On page update, serviceWorker order subscriber to reload

such serviceworker code fail :

   if (client.url == self.registration.scope && 'focus' in client) {
                client.postMessage('reload'); // DOESN'T WORK
                return client.focus();
            }

Failing code on android/chrome for setinterval :

    setInterval(async function(){
    const response = await fetch('/lastupdatetimestamp', {
        method: 'get',
        headers: { 'Content-Type': 'application/json' }
    });
    const json= await response.json();
    if(LASTUP<json.up.lastdate){
        window.location.reload()
        LASTUP=json.up.lastdate
    }

}, 30000);

Any idea ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I finally founded a first step :

server send push -> serviceworker show notification -> click on notification -> goes open window and reload

in the serviceWorker.js

self.addEventListener('push', function (event) { ... }

self.addEventListener('notificationclick', async function(event) {
event.notification.close();
await event.waitUntil(clients.matchAll({
    type: "window",
    includeUncontrolled: true
}).then(function(clientList) {
    for (var i = 0; i < clientList.length; i++) {
        var client = clientList[i];
        if (client.url == self.registration.scope && 'focus' in client) {  //
            client.postMessage('reload'); // <= TRIGGER 'RELOAD' EVENT HERE
            return client.focus();
        }
    }
    if (clients.openWindow) {
        return clients.openWindow(self.registration.scope);
    }
}));
});

in the app.js

function initPostMessageListener() {
console.log("event listener message")
navigator.serviceWorker.addEventListener('message', function(e) {
  var message = e.data;
  console.log("ON A UN MESSAGE")
  switch (message) {
    case 'reload':
      window.location.reload(true);
      break;
    default:
      console.warn("Message '" + message + "' not handled.");
      break;
  }
});
}

call initPostMessageListener() in the app.js where the SW is registered

So the SW.js handle the notificationClick then open the browser window if exist and reload it

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda