捕获 window.onbeforeunload 确认对话框的结果

发布于 2024-10-26 06:43:40 字数 1162 浏览 6 评论 0原文

有没有一种方法可以捕获 window.onbeforeunload 确认对话框的结果,如 Stack Overflow 中的下面所示(在离开“提问”页面而不发布问题时会发生这种情况)?

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

window.onbeforeunload 确认对话框

据推测,如果他们在事件触发后仍在违规页面上,他们会选择留下来并你也许可以通过观察 js 的顺序来弄清楚这一点。但是我想知道如何确定他们是否点击了“离开此页面”

我已经实现了如下所示:

// 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。

我本质上是在尝试实现类似 Gmail 的起草实现,其中如果用户离开带有他们已更改但未保存的表单的页面,他们会看到类似的对话框。如果他们选择放弃更改并离开页面,我需要从数据库中清理一些临时记录(我正在考虑 AJAX 调用,或者只是使用 delete 标志提交表单)然后送他们上路。

我的问题还涉及:

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

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)?

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.

window.onbeforeunload confirmation dialog

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')

note I'm using jQuery within my site.

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.

My question also relates to:

jQuery AJAX call in onunload handler firing AFTER getting the page on a manual refresh. How do I guarantee onunload happens first?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

时间你老了 2024-11-02 06:43:40

您可以使用 window.onbeforeunload 进行退出确认,但没有找出用户单击了哪个按钮的方法。

引用jvenema 的早期回复:

主要目的
beforeunload 用于类似的事情
允许用户选择保存
在更改丢失之前进行更改。

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

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

To quote an earlier response from jvenema from this thread:

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 [...]

七色彩虹 2024-11-02 06:43:40

这个怎么样:

$( window ).bind( 'beforeunload' , function( event ) {
    setTimeout( function() {
        alert( 'Hi againe!' );
    } );
    return '';
} ).bind( 'unload', function( event ) {
    alert( 'Goodby!' );
} );

How about this:

$( window ).bind( 'beforeunload' , function( event ) {
    setTimeout( function() {
        alert( 'Hi againe!' );
    } );
    return '';
} ).bind( 'unload', function( event ) {
    alert( 'Goodby!' );
} );
大海や 2024-11-02 06:43:40

聚会迟到了,但我发现下面的代码(TypeScript)是一个不错的方法来检测人们是否在确认对话窗口上点击了“确定”。

public listenToUnloadEvents(): void {

  window.addEventListener('beforeunload', (e) => {
    const confirmationMessage = '\o/';

    (e || window.event).returnValue = confirmationMessage;     // Gecko + IE
    return confirmationMessage;                                // Webkit, Safari, Chrome etc.
  });

  window.addEventListener('unload', () => {

    this.sendNotification(Action.LEFT)
  });
}

我不确定您需要在 unload 事件中运行代码多少时间,但在本例中,我通过 Socket.io 发送通知,因此完成速度非常快。

至于检测该通知的取消,正如其他人提到的,创建像 let didEnterBeforeUnload = false 这样的全局变量可以在 beforeunload 时设置为 true代码> 事件触发。之后,通过创建第三个事件,就像这样(同样,在 TypeScript 中),您可以推断用户按下了取消。

window.addEventListener('focus', (e) => {

  if (didEnterBeforeUnload) {
    console.log('pressed cancel')
  }

  didEnterBeforeUnload = false
});

不过顺便说一句,除非您与页面进行了交互,否则这些事件不会 (iirc) 触发。因此,在测试期间尝试导航离开之前,请确保单击或点击进入页面。

我希望这对其他人有帮助!

Late to the party, but I found the following code (in TypeScript) to be a decent way to detect if the person clicked on 'Ok' on that confirmation dialogue window.

public listenToUnloadEvents(): void {

  window.addEventListener('beforeunload', (e) => {
    const confirmationMessage = '\o/';

    (e || window.event).returnValue = confirmationMessage;     // Gecko + IE
    return confirmationMessage;                                // Webkit, Safari, Chrome etc.
  });

  window.addEventListener('unload', () => {

    this.sendNotification(Action.LEFT)
  });
}

I'm not sure how much time you have to run code in the unload event, but in this instance, I am sending a notification through Socket.io, so it's very quick at completing.

As for detecting the cancel on that notification, as someone else mentioned, creating a global variable like let didEnterBeforeUnload = false could be set to true when the beforeunload event fires. After this, by creating the third event, like so (again, in TypeScript), you can infer the user pressing cancel

window.addEventListener('focus', (e) => {

  if (didEnterBeforeUnload) {
    console.log('pressed cancel')
  }

  didEnterBeforeUnload = false
});

As a side-note though, these events won't (iirc) fire unless you have interacted with the page. So make sure to click or tap into the page before trying to navigate away during your testing.

I hope this helps anyone else out there!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文