我想在用户离开当前页面时向服务器发送一条消息,我现在正在使用 .unload 但结果不可靠,即使在其文档中也是如此:
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.
我应该使用 beforeunload 事件吗?靠谱吗?
最佳答案
是的,beforeunload
比较靠谱,但是一定要直接赋值(不是通过jQuery绑定(bind)),像这样:
window.onbeforeunload = function() { /* do stuff */ };
unload
事件本身并不意味着要完成的工作,只是清理对象......随着垃圾收集器变得越来越好,浏览器甚至没有理由触发 unload
事件。
另请注意,对于您的特定情况,您必须向服务器发出同步请求...否则浏览器仍不会等待 AJAX 调用完成。
关于javascript - jquery:卸载还是卸载之前?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4376596/