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

178
Visualizações
Async Event on Tab Close

I'm looking for a solid solution to carry out an asynchronous event on a tab close in JavaScript

For context, I have a site with multiple (thousands) of pages that should only allow one user to edit a page at a time (i.e. two users can't be writing to the same page at once). So, when a user opens a page, I make a fetch call to set a database flag for that page to mark it as locked.

Ideally, when the tab/window is closed or the page is left, I need to unset that locked flag; calling another async fetch event to do so. I'm familiar with window.onunload and window.onbeforeunload and currently use those to try to call the fetch to achieve this, but it seems this only works about half of the time. The other half of the time, the page will never unset the lock which causes major issues when other users need to access the page after

My code:

    window.addEventListener('beforeunload', (ev) => {
      ev.preventDefault();
      if (condition) {
        postToURL(`/url/to/unlock/page`);    //postToURL is a custom function that essentially calls 'fetch'. Using the 'await' keyword seemed to have no effect here
      }
      return;
    });

My question is, is there a more consistent way to do this? With a site that requires multiple users to constantly leave and open these pages, I need a more accurate way to handle this. Any help would be greatly appreciated, thanks!

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

0

The Beacon API was made for this scenario. It will send a request independent of the page closing.

https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API

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