window.close()和beforeunload事件 [英] window.close() and the beforeunload event

查看:1217
本文介绍了window.close()和beforeunload事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当用户关闭浏览器窗口时,我都需要清除一些会话变量.可以通过两种方式关闭窗口:

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

  • 按下窗口关闭按钮的正常方式
  • 通过按下窗口内的自定义按钮

我正在使用jQuery,因此侦听器为:

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();

问题是关闭窗口的第二种方法仅触发FF中的beforeunload事件.在Chrome中,第二种方法仅在某些时候有效,而在Safari中则根本不起作用.有什么想法吗?

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?

解决方案(到目前为止):

// 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);
});

这在大多数浏览器中都适用:IE8 +,Chrome,FF,当使用window.close()和/或本机浏览器按钮关闭窗口时

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

如果窗口被本机浏览器窗口关闭,它也可以在Safari中使用.

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

根本无法在Opera中工作.

Does not work in Opera at all.

推荐答案

尝试一下

$(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.

这篇关于window.close()和beforeunload事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆