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

221
Vistas
Distinguir entre diferentes tipos de eventos antes de la descarga

En JavaScript, ¿es posible distinguir entre los eventos beforeunload que fueron activados por el usuario al cerrar una pestaña del navegador y hacer clic en un enlace de mailto ?

Básicamente, me gustaría hacer esto:

 window.addEventListener("beforeunload", function (e) { if(browserTabClosed) { // Do one thing } else if (mailtoLinkClicked) { // Do a different thing } }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Encontré una solución mirando el evento ( e a continuación) que se pasa:

 window.addEventListener("beforeunload", function (e) { // We can use `e.target.activeElement.nodeName` // to check what triggered the passed-in event. // - If triggered by closing a browser tab: The value is "BODY" // - If triggered by clicking a link: The value is "A" const isLinkClicked = (e.target.activeElement.nodeName === "A"); // If triggered by clicking a link if (isLinkClicked) { // Do one thing } // If triggered by closing the browser tab else { // Do a different thing } }
about 4 years ago · Juan Pablo Isaza Denunciar

0

El método beforeunload tiene un comportamiento inestable entre los navegadores, la razón es que las implementaciones del navegador intentan evitar las ventanas emergentes y otros códigos maliciosos que se ejecutan dentro de este controlador.

En realidad, no existe una forma general (entre navegadores) de detectar qué desencadenó el evento beforeunload .

Dijo que, en su caso, solo podría detectar un clic en la window para discriminar entre los dos comportamientos requeridos:

 window.__exit_with_link = false; window.addEventListener('click', function (e) { // user clicked a link var isLink = e.target.tagName.toLowerCase() === 'a'; // check if the link has this page as target: // if is targeting a popup/iframe/blank page // the beforeunload on this page // would not be triggered anyway var isSelf = !a.target.target || a.target.target.toLowerCase() === '_self'; if (isLink && isSelf) { window.__exit_with_link = true; // ensure reset after a little time setTimeout(function(){ window.__exit_with_link = false; }, 50); } else { window.__exit_with_link = false; } }); window.addEventListener('beforeunload', function (e) { if (window.__exit_with_link) { // the user exited the page by clicking a link } else { // the user exited the page for any other reason } }

Obviamente no es la forma correcta, pero sigue funcionando.

De la misma manera, puede agregar otros controladores para verificar otras razones por las que el usuario abandonó la página (por ejemplo, teclado CTRL-R para actualizar, etc.)

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