Treat event when closing browser

Asked

Viewed 7,000 times

6

I am having problems regarding this event handling when closing the browser using javascript.

I did some research and found an idea through onbeforeunload:

<script> 

    window.onbeforeunload = fecharJanela  

    function fecharJanela(){  
        return "Você realmente deseja fechar a janela?"  
    }  

</script> 

But with this script when updating the page or even when I click to direct to another link of the same domain it asks if I really want to close the page, which in my case is not interesting.

Does anyone have an idea of how I can capture the event only when the browser or tab is closed?

If I can get a boolean return at the time of this event to handle it in my javascript, since I will have to show a custom modal before the browser is closed.

Thanks!

  • Hello Samuel, unfortunately it is impossible to capture the closing event, the only events fired are beforeunload and Unload, which are actually triggered even when a pagination occurs (changes of page or site) in the same tab. There is no specific event for this, all attempts to treat this are gambiarras using the event mouseout in the window

1 answer

5

To open a prompt asking if Voce wants to quit:

window.onbeforeunload = function(){
  return 'Você tem certeza que deseja sair?';
};

If you have used Jquery:

$(window).bind('beforeunload', function(){
  return 'Você tem certeza que deseja sair?';
});

In case you wanted to run something before leaving the page

Remember that you will not be able to redirect the person to another link for security reasons

window.onunload = function() {
    alert('Valeu, falow.');
    //Seu código aqui
}

If you have used Jquery:

$(window).unload(function(){
  alert('Valeu, falow.');
  //Seu código aqui
});

I hope I helped! Abs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.