Handling event when closing browser

6

I'm having problems with this event handling when closing the browser using javascript.

I researched a little 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 link to another link in 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 how I can capture the event only the moment the browser or tab is closed?

If I get a Boolean return the moment there is this event to handle this in my javascript, since I'll have to show a custom modal before the browser closes.

Thanks!

    
asked by anonymous 25.06.2015 / 14:16

1 answer

5

To open a prompt asking if you want to exit:

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

If you have Jquery:

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

If you wanted to run something before you left the page

Remembering that you can not redirect the person to another link for security reasons

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

If you have Jquery:

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

I hope I have helped! Abs!

    
25.06.2015 / 20:31