Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: unload or beforeunload?

I want to post an message to the server when user navigate off from the current page, I am using .unload right now but the result is unreliable, even in its document is said true:

The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers, and contrasted with the proprietary beforeunload event.

Should I use beforeunload event? Is it reliable?

like image 805
Bin Chen Avatar asked Dec 07 '10 12:12

Bin Chen


People also ask

What is the difference between unload and Beforeunload?

beforeunload event – the user is leaving: we can check if the user saved the changes and ask them whether they really want to leave. unload – the user almost left, but we still can initiate some operations, such as sending out statistics.

Is Beforeunload deprecated?

Deprecated. Not for use in new websites.

Does Beforeunload work on mobile?

according to the MDN docs, beforeunload and load events are supported since Chrome for Androied version 18 and Firefox for Android version 4. please provide the minimal portion of the related code so we can help you better.

What is Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.


1 Answers

Yes, beforeunload is more reliable, but be sure to assign it directly (not bound through jQuery), like this:

window.onbeforeunload = function() { /* do stuff */ }; 

The unload event itself wasn't meant for work to be done, only cleanup of objects...as garbage collectors get better and better, there's less reason for the browser to even fire the unload event.

Also be aware that for your specific case you'd have to make a synchronous request to the server...otherwise the browser still won't wait for the AJAX call to complete.

like image 116
Nick Craver Avatar answered Oct 02 '22 09:10

Nick Craver