Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...