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 } }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 } }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.)