捕获window.onbeforeunload确认对话框的结果 [英] Capturing result of window.onbeforeunload confirmation dialog

查看:950
本文介绍了捕获window.onbeforeunload确认对话框的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法捕获window.onbeforeunload确认对话框的结果,如Stack Overflow中的下一个(当离开'Ask Question'页面而没有发布问题时会发生这种情况)?

Is there a way to capture to result of the window.onbeforeunload confirmation dialog like the one below from Stack Overflow (this happens when leaving the 'Ask Question' page without posting the question)?

这是它在Chrome中的显示方式,我相信它在其他浏览器中略有不同,但你总是有某种形式的是/否按钮。

This is how it appears in Chrome, I believe it's slightly different in other browsers, but you always have some form of yes/no buttons.

据推测,如果他们在事件被触发后他们仍然在违规页面上,他们选择留下来,你可以通过观察js的顺序来解决这个问题。但是我想知道如何确定他们是否点击了离开此页面

Presumably if they're still on the offending page after the event has been triggered they chose to stay and you could probably figure this out by watching the sequence of js. However I would like to know how to determine if they clicked "Leave this page"?

我已经实现了如下所示:

I've implemented this like below:

// concept taken from SO implementation
function setConfirmUnload(showMessage, message) {
    window.onbeforeunload = showMessage ? (message ? message : "this is a default message") : null;
}

// pseudo code
listen to changes on inputs
if any inputs fire a change event
   call setConfirmUnload(true, 'My warning message')

注意我在我的网站中使用jQuery。

note I'm using jQuery within my site.

我实际上是在尝试实现一个类似于草拟实现的Gmail,其中如果用户离开带有表单的页面,他们已经对其进行了更改,而没有保存它们会被加热类似的对话。如果他们选择丢弃他们的更改并离开页面,我需要清理数据库中的一些临时记录(我正在考虑一个AJAX调用,或者只是使用 delete flag)然后在途中发送。

I'm essentially trying to implement a Gmail like drafting implementation, wherein if a user leaves a page with a form they've made changes to without saving they're warmed with a similar dialog. If they choose to discard they're changes and leave the page, I need to clean up some temporary records from the database (I'm thinking an AJAX call, or simply submitting the form with a delete flag) then sending them on their way.

我的问题还涉及:

jQuery AJAX调用onunload处理程序在手动刷新后获取页面后触发。我如何保证首先发生onunload?

推荐答案

您可以使用 window.onbeforeunload 但是没有办法找出用户点击的按钮。

You can have the exit confirmation using window.onbeforeunload but there isn't a way to find out which button the user clicked on.

来自这个主题的jvenema



beforeunload的主要用途是像
这样的东西允许用户选择在更改丢失之前保存
更改。

The primary purpose for the beforeunload is for things like allowing the users the option to save changes before their changes are lost.

此外,如果您的用户离开,
已经太晚了[...]

Besides, if your users are leaving, it's already too late [...]

这篇关于捕获window.onbeforeunload确认对话框的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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