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

242
Visualizações
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 Respostas
Responde à pergunta

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 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