Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

javascript - 如何捕获浏览器窗口关闭事件?(How to capture the browser window close event?)

I want to capture the browser window/tab close event.(我想捕获浏览器窗口/选项卡关闭事件。)

I have tried the following with jQuery:(我已经尝试使用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.(我想要一个仅在用户关闭窗口时才触发的事件。)   ask by khelll translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The beforeunload event fires whenever the user leaves your page for any reason.(每当用户出于任何原因离开您的页面时,就会触发beforeunload事件。)

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.(例如,如果用户提交表单,单击链接,关闭窗口(或选项卡)或使用地址栏,搜索框或书签进入新页面,则将触发该事件。)

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

For jQuery versions older than 1.7, try this:(对于1.7之前的jQuery版本,请尝试以下操作:)

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.(live方法不适用于submit事件,因此,如果添加新表单,则还需要将处理程序绑定到该表单。)

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.(你可以通过记录的时间解决这个问题submitclick事件,并检查是否beforeunload发生超过几秒钟后。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...