window.close()和beforeunload事件

编程入门 行业动态 更新时间:2024-10-26 02:31:50
本文介绍了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事件

本文发布于:2023-11-09 15:30:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572735.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件   window   close   beforeunload

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!