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

246
Vistas
How to call a function before leaving page via HTML <a> target Attribute with Javascript

I have an HTML tag with a target attribute. The issue is that I want to prevent the user leaving my site this way without saving his changes.

I tried

window.onbeforeunload = function(){
  myfun();
  return 'Are you sure you want to leave?';
};

Also changed my code to:

window.addEventListener('onbeforeunload', (e) => {
      e.preventDefault();
      console.log('Inside event')
    })

But that didn't do it...

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The return 'string' method does not work reliably everywhere. Most, if not all Web browsers won't show a custom message. And you also need to call preventDefault on the event:

window.onbeforeunload = (event) => {
  myfun();
  event.preventDefault();
  return 'Are you sure you want to leave?';
};

EDIT This will not work using alert, confirm or prompt because it will override the browser's default message before displayed. You can do anything else though:

window.onbeforeunload = function(e){
  console.log('Leaving...');
  e.preventDefault();
};
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