jquery: unload or beforeunload?

前端 未结 1 544
醉酒成梦
醉酒成梦 2020-11-30 02:19

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

相关标签:
1条回答
  • 2020-11-30 02:56

    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.

    0 讨论(0)
提交回复
热议问题