Why jQuery sometimes overwrites window.onbeforeunload?

大憨熊 提交于 2019-12-05 23:52:10

问题


I am having strange problem with jQuery (1.6.x). I have this simple call on my page:

window.onbeforeunload = function() { return 'Are you sure ?'; };

But it doesn't work, because as I've found out, jQuery overwrites content of the window.onbeforeunload. In JS console, I can see that window.onbeforeunload contains piece of jQuery code:

function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
    jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined;
};

Is there a way I can find why and where jQuery overwrites my onbeforeunload function ? When I try to run empty jsfiddle with just jQuery loaded and with my onbeforeunload function, it works as expected.

Any hints will be appreciated. Thanks in advance.

EDIT:

Just in case, somebody suggests using:

$(window).bind('beforeunload', function() { return 'Are you sure';} );

I've already tried it and it behaves the same way as using pure javascript.


回答1:


Ok, I've finally figured a solution, which is probably not the cleanest one - because I don't know the exact cause of the problem - but it works. I've put my beforeunload function into jQuery's load function so it is executed after DOM and other elements are loaded.

$(window).load(function () {
  $(window).bind('beforeunload', function() { return 'Are you sure ?';} );
});



回答2:


You might have some luck trying a setTimeout(function(){ ... },0), I ran into the same problem and this worked as a viable solution.



来源:https://stackoverflow.com/questions/7481048/why-jquery-sometimes-overwrites-window-onbeforeunload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!