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

288
Visualizações
Record if the user clicked 'cancel' on Javascript 'beforeunload' event

I'm trying to perform some actions if the user closes the browser tab. Below is my code.

function myfun(){
  console.log('action performed')
}

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

My code works, but the issue i'm facing is, on the prompt if the user click on the cancel button doesn't close the tab, my function still runs. Is there way to record that the user has clicked on the cancel button ?

I've tried to modify the 'myfun' function as below, but didn't helped.

function myfun(){
  if(window.close()){
    console.log('action perfomed')
  }
}
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can use the unload event. Since most browser delete the log of a page once it's unloaded, I replaced it with a localStorage example.

function myfun(){
  localStorage.setItem('myCat', 'Tom');
}

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

window.onunload = myfun;
if(localStorage.getItem("myCat")!=null)
  alert("Last time this page was closed the unload event was called!");
localStorage.setItem('myCat', null);

Unload event will not always be fired, as Mozilla states :

Especially on mobile, the unload event is not reliably fired. For example, the unload event is not fired at all in the following scenario:

  1. A mobile user visits your page.
  2. The user then switches to a different app.
  3. Later, the user closes the browser from the app manager.

It's better to use visibilitychange event or pagehide event, even though they do not fully replace the unload event.

Also, the unload event is not compatible with the back/forward cache (bfcache), because many pages using this event assume that the page will not continue to exist after the event is fired. To combat this, some browsers (such as Firefox) will not place pages in the bfcache if they have unload listeners, and this is bad for performance. Others, such as Chrome, will not fire the unload when a user navigates away.

The best event to use to signal the end of a user's session is the visibilitychange event. In browsers that don't support visibilitychange the next-best alternative is the pagehide event, which is also not fired reliably, but which is bfcache-compatible.

If you're specifically trying to detect page unload events, it's best to listen for the pagehide event.

about 4 years ago · Santiago Trujillo Relatório

0

I think it's not possible to check whether user pressed cancel button. In other way you can use onunload event as per below code.

window.onunload = function(e) {
      console.log("unload event");
    };

If the user clicks on reload then this will be called.

about 4 years ago · Santiago Trujillo 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