如何知道用户是否在 Javascript onbeforeunload 对话框上单击了取消?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4650692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:27:24  来源:igfitidea点击:

Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?

javascriptjquerydom-eventsonbeforeunload

提问by at.

I am popping up a dialog box when someone tries to navigate away from a particular page without having saved their work. I use Javascript's onbeforeunload event, works great.

当有人试图离开特定页面而没有保存他们的工作时,我会弹出一个对话框。我使用 Javascript 的 onbeforeunload 事件,效果很好。

Now I want to run some Javascript code when the user clicks "Cancel" on the dialog that comes up (saying they don't want to navigate away from the page).

现在我想在用户点击出现的对话框上的“取消”时运行一些 Javascript 代码(说他们不想离开页面)。

Is this possible? I'm using jQuery as well, so is there maybe an event like beforeunloadcancel I can bind to?

这可能吗?我也在使用 jQuery,那么可能有一个像 beforeunloadcancel 这样的事件我可以绑定到吗?

UPDATE: The idea is to actually save and direct users to a different webpage if they chose cancel

更新:如果他们选择取消,这个想法实际上是保存并引导用户到不同的网页

回答by jAndy

You can do it like this:

你可以这样做:

$(function() {
    $(window).bind('beforeunload', function() {
        setTimeout(function() {
            setTimeout(function() {
                $(document.body).css('background-color', 'red');
            }, 1000);
        },1);
        return 'are you sure';
    });
}); 

The code within the first setTimeoutmethod has a delay of 1ms. This is just to add the function into the UI queue. Since setTimeoutruns asynchronously the Javascript interpreter will continue by directly calling the returnstatement, which in turn triggers the browsers modal dialog. This will block the UI queueand the code from the first setTimeoutis not executed, until the modal is closed. If the user pressed cancel, it will trigger another setTimeout which fires in about one second. If the user confirmed with ok, the user will redirect and the second setTimeout is never fired.

setTimeout一种方法中的代码有 1 毫秒的延迟。这只是将函数添加到UI queue. 由于setTimeout异步运行,Javascript 解释器将继续直接调用该return语句,进而触发浏览器modal dialog。这将阻塞UI queue并且setTimeout不会执行第一个代码,直到模态关闭。如果用户按下取消,它会触发另一个 setTimeout,它会在大约一秒钟内触发。如果用户确认 ok,则用户将重定向并且永远不会触发第二个 setTimeout。

example: http://www.jsfiddle.net/NdyGJ/2/

示例:http: //www.jsfiddle.net/NdyGJ/2/

回答by 99 Problems - Syntax ain't one

I know this question is old now, but in case anyone is still having issues with this, I have found a solution that seems to work for me,

我知道这个问题现在已经过时了,但如果有人仍然对此有疑问,我找到了一个似乎对我有用的解决方案,

Basically the unloadevent is fired after the beforeunloadevent. We can use this to cancel a timeout created in the beforeunloadevent, modifying jAndy's answer:

基本上unload事件是在beforeunload事件发生后触发的。我们可以使用它来取消beforeunload事件中创建的超时,修改 jAndy 的回答:

$(function() {
    var beforeUnloadTimeout = 0 ;
    $(window).bind('beforeunload', function()  {
        console.log('beforeunload');
        beforeUnloadTimeout = setTimeout(function() {
            console.log('settimeout function');
            $(document.body).css('background-color', 'red');
        },500);
        return 'are you sure';
    });
    $(window).bind('unload', function() {
        console.log('unload');
        if(typeof beforeUnloadTimeout !=='undefined' && beforeUnloadTimeout != 0)
            clearTimeout(beforeUnloadTimeout);
    });
}); 

EDIT:jsfiddle here

编辑:jsfiddle在这里

回答by Juan Mendes

Not possible. Maybe someone will prove me wrong... What code do you want to run? Do you want to auto-save when they click cancel? That sounds counter-intuitive. If you don't already auto-save, I think it makes little sense to auto-save when they hit "Cancel". Maybe you could highlight the save button in your onbeforeunload handler so the user sees what they need to do before navigating away.

不可能。也许有人会证明我错了...你想运行什么代码?你想在他们点击取消时自动保存吗?这听起来违反直觉。如果您还没有自动保存,我认为当他们点击“取消”时自动保存没有意义。也许您可以在 onbeforeunload 处理程序中突出显示保存按钮,以便用户在导航离开之前看到他们需要做什么。

回答by Barlow Tucker

I didn't think it was possible, but just tried this idea and it works (although it is some what of a hack and may not work the same in all browsers):

我不认为这是可能的,但只是尝试了这个想法并且它有效(尽管它是一种黑客行为,并且可能在所有浏览器中都不同):

window.onbeforeunload = function () {   
  $('body').mousemove(checkunload);
  return "Sure thing"; 
};

function checkunload() {   
  $('body').unbind("mousemove");
  //ADD CODE TO RUN IF CANCEL WAS CLICKED
}

回答by jyoti

window.onbeforeunload  = function() {
    if (confirm('Do you want to navigate away from this page?')) {
        alert('Saving work...(OK clicked)')
    } else {
        alert('Saving work...(canceled clicked)')
        return false
    }
 }

with this code also if user clicks on 'Cancel' in IE8 the default navigation dialog will appear.

使用此代码,如果用户在 IE8 中单击“取消”,也会出现默认导航对话框。