window.close() and the beforeunload event

点点圈 提交于 2019-12-11 11:24:29

问题


I need to clear some session variables whenever user closes the browser window. The window can be closed in two ways:

  • the normal way by pressing the window close button
  • by pressing a custom button inside the window

I am using jQuery, so the listener is:

// clear some session variables
$(window).bind('beforeunload', function() {
    makeAjaxCall(some, params);
});

The window is closed by calling a function that eventually executes:

window.close();

The problem is that the second way to close the window only triggers the beforeunload event in FF. In Chrome the second way works only sometimes, in Safari it does not work at all. Any thoughts?


SOLUTION (so far):

// clear search filter whenever the user closes the window
$(window).on('beforeunload', function() {   // most browsers except Safari
    doSomeMagic(param);
    return;
}).on('unload', function() {         // Chrome
    doSomeMagic(param);
});

This works in most browsers: IE8+, Chrome, FF when closing window with window.close() and/or native browser button

It also works in Safari if window is closed by native browser window.

Does not work in Opera at all.


回答1:


Try this

$(window).on('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

$(window).on('unload', function(){
     logout();

});

This solution works in all browsers and I have tested it.



来源:https://stackoverflow.com/questions/21576316/window-close-and-the-beforeunload-event

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