How to execute a javascript function in closing the browser?

3

I'm developing a web application and need to perform a function when the client clicks the browser's X or simply closes it.

To be more specific, I need to execute an ajax call on this closing.

Is there any way to do this?

    
asked by anonymous 26.06.2014 / 22:29

1 answer

8

It is not possible to distinguish between the user clicking on the CLOSE of the browser, when it closes the tab or when it leaves your site through a link, but fortunately it is possible to detect when one of these events happens, and it is through the events onunload and onbeforeunload.

  • onunload : runs in competition with browser closure. It can be bad in browsers like IE, because sometimes it just ignores the javascript you want to run at the same time.

  • onbeforeunload (recommended): run before the browser starts closing. It is most recommended because your JS can run before, and avoids some problems with IE.

I recommend using jQuery because you already handle possible differences between browsers:

link

    
26.06.2014 / 22:42