How to execute a javascript function in the browser closure?

Asked

Viewed 1,901 times

3

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

To be more specific I need to execute an ajax call at this close.

Is there any way to do that?

  • 1

    Do you want to know how to call this function when the page is closed (which event should you use)? Or wants to know how to do the function that makes the AJAX call?

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: run in competition with the browser close. 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): executed before the browser starts closing. It is more 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:

http://api.jquery.com/unload/

Browser other questions tagged

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