使用onbeforeunload确认时是否可以捕获用户的答案? [英] Is it possible to capture the user's answer when using onbeforeunload confirmation?

查看:85
本文介绍了使用onbeforeunload确认时是否可以捕获用户的答案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要警告用户,他们离开页面时会丢失信息.使用onbeforeunload事件可以轻松完成此操作.我的问题是,如果用户决定离开,我想采取一些措施.

I need to warn users that they will lose information when leaving a page. This is easily done using the onbeforeunload event. My problem is that I want to take some action if the user decides to leave.

这是一个示例(我正在使用jquery,因为它无论如何都已加载):

Here's an example (I'm using jquery because it's loaded anyway):

$(window).on('beforeunload', function(e){
    return "Do you really want to leave?";
});

我想做的是这样的事情(我知道这段代码不起作用,这只是一个示例来说明我正在尝试做的事情):

What I would like to do is something like this (this code doesn't work, I know, it's just an example to illustrate what I'm trying to do):

$(window).on('beforeunload', function(e){
    // Ask for user confirmation
    var bUserAnswer = confirm("Do you really want to leave?");

    if(bUserAnswer)
    {
        // Do something...
    }
    else
    {
        // Do something else...
    }
    // Close everything if the user decides to leave...
    return bUserAnswer;
});

我什至不知道我在这里尝试做的事情是否可能...谷歌搜索并没有给我任何一种指示,所以我转向了我最喜欢的专家组!

I have no idea if what I'm trying to do here is even possible... Googling around didn't give me any indication one way or the other so I'm turning to my favorite group of experts!

知道我该怎么做吗?

谢谢!

推荐答案

离开页面时,事件beforeunloadunload依次执行.当然,如果beforeunload事件未完成,则unload事件不会.

When leaving the page, the events beforeunload and unload execute, in that order. Of course, if the beforeunload event doesn't complete, the unload event won't.

beforeunload事件未完成的方式是当用户单击停留在页面"按钮而不是离开页面"时(如果该对话框显示给他们,就像您的代码一样).

The way the beforeunload event doesn't complete is when the user clicks the "Stay on Page" button instead of "Leave Page" (if that dialog is presented to them, like in your code).

因此,如果您知道他们总是会离开他们的页面,则unload事件执行的唯一方法是如果未阻止beforeunload事件(由用户执行) ).

So if you know that the possibility for them to not leave the page will always be presented to them, the only way for the unload event to execute is if the beforeunload event isn't prevented (by the user).

因此,当用户实际选择将页面留在unload事件中时,您应该能够将要执行的所有代码置于该位置.

Therefore, you should be able to put any code that you want to execute when the user actually chooses to leave the page in the unload event.

至于是否知道用户是否决定停留在页面上,我不确定如何捕获它:)

As for knowing if the user decided to stay on the page, I'm not sure how to catch it :)

这篇关于使用onbeforeunload确认时是否可以捕获用户的答案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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