我正在尝试在用户离开网站时在后台跟踪数据。这适用于 firefox 和 chrome。但不适用于 Internet Explorer。在 Internet Explorer 上卸载事件之前使用的正确方法是什么?
$(window).bind('beforeunload', function () {
$.post("track.php", {
async: false,
ip: ip,
plansclick: plansclick,
});
});
似乎是 beforeunload
事件的问题。这在 jQuery.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
比unload
靠谱,但是一定要直接赋值(不是通过jQuery绑定(bind)),像这样:
window.onbeforeunload = function() {/* 做一些事情 */};
卸载事件本身并不意味着要完成的工作,只是清理对象......随着垃圾收集器变得越来越好,浏览器甚至触发卸载事件的理由越来越少。
因此您可以尝试将您的代码转换为:
window.onbeforeunload = function () {
$.post("track.php", {
async: false,
ip: ip,
plansclick: plansclick,
});
};
但是,此功能似乎无法在任何浏览器中得到保证。
Possible Fix for jQuery.onbeforeunload
Duplicate issue on stackoverflow
Duplicate issue on stackoverflow 2
Duplicate issue on stackoverflow 3