Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda