如何捕获浏览器窗口关闭事件

如何捕获浏览器窗口关闭事件

本文介绍了如何捕获浏览器窗口关闭事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想捕捉的浏览器窗口/标签关闭事件。
我曾尝试以下使用jQuery:

I want to capture the browser window/tab close event.I have tried the following with jQuery:

jQuery(window).bind(
    "beforeunload",
    function() {
        return confirm("Do you really want to close?")
    }
)

但它适用于表单提交为好,这是不是我想要的。我想触发只有当用户关闭窗口的事件。

But it works on form submission as well, which is not what I want. I want an event that triggers only when the user closes the window.

推荐答案

每当用户离开你的页面以任何理由的 beforeunload 事件触发。

The beforeunload event fires whenever the user leaves your page for any reason.

例如,它会在用户提交表单,点击链接,关闭该窗口(或标签)解雇,或者去使用地址栏,搜索框或书签了新的一页。

For example, it will be fired if the user submits a form, clicks a link, closes the window (or tab), or goes to a new page using the address bar, search box, or a bookmark.

您可以用下面的code排除表单提交和超链接(除了其他帧):

You could exclude form submissions and hyperlinks (except from other frames) with the following code:

var inFormOrLink;
$('a').on('click', function() { inFormOrLink = true; });
$('form').on('submit', function() { inFormOrLink = true; });

$(window).on("beforeunload", function() {
    return inFormOrLink ? "Do you really want to close?" : null;
})

有关比1.7更旧版本的jQuery,试试这个:

For jQuery versions older than 1.7, try this:

var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });

$(window).bind("beforeunload", function() {
    return inFormOrLink ? "Do you really want to close?" : null;
})

生活方法不使用提交事件的工作,因此,如果您添加一个新的形式,你会需要处理程序绑定到它。

The live method doesn't work with the submit event, so if you add a new form, you'll need to bind the handler to it as well.

请注意,如果一个不同的事件处理程序取消提交或导航,你将失去的确认提示如果窗口实际上是后关闭。你可以解决这个问题通过记录在提交点击事件,并检查是否 beforeunload 发生超过几秒钟后多。

Note that if a different event handler cancels the submit or navigation, you will lose the confirmation prompt if the window is actually closed later. You could fix that by recording the time in the submit and click events, and checking if the beforeunload happens more than a couple of seconds later.

这篇关于如何捕获浏览器窗口关闭事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 20:57