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

发布于 2024-10-11 04:08:10 字数 274 浏览 8 评论 0原文

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

现在,当用户单击出现的对话框中的“取消”(表示他们不想离开该页面)时,我想运行一些 Javascript 代码。

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

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

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.

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

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

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

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

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

发布评论

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

评论(6

长亭外,古道边 2024-10-18 04:08:10

您可以这样做:

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

第一个 setTimeout 方法中的代码有 1ms 的延迟。这只是将该函数添加到 UI 队列 中。由于 setTimeout 异步运行,Javascript 解释器将通过直接调用 return 语句继续,从而触发浏览器模态对话框。这将阻塞 UI 队列,并且第一个 setTimeout 中的代码不会执行,直到模式关闭。如果用户按下“取消”,它将触发另一个 setTimeout,该事件会在大约一秒内触发。如果用户确认“确定”,用户将重定向,并且第二个 setTimeout 永远不会被触发。

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

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 setTimeout method has a delay of 1ms. This is just to add the function into the UI queue. Since setTimeout runs asynchronously the Javascript interpreter will continue by directly calling the return statement, which in turn triggers the browsers modal dialog. This will block the UI queue and the code from the first setTimeout is 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.

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

旧时光的容颜 2024-10-18 04:08:10

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

基本上 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);
    });
}); 

编辑: jsfiddle 在这里

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 unload event is fired after the beforeunload event. We can use this to cancel a timeout created in the beforeunload event, modifying jAndy's answer:

$(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

她比我温柔 2024-10-18 04:08:10

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

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.

紙鸢 2024-10-18 04:08:10

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

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

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

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
}
深陷 2024-10-18 04:08:10

另一种变化
第一个 setTimeout 等待用户响应浏览器的离开/取消弹出窗口。第二个 setTimeout 等待 1 秒,然后仅在用户取消时调用 CancelSelected。否则页面会被卸载并且setTimeout会丢失。

window.onbeforeunload  = function(e) {
    e.returnValue = "message to user";
    setTimeout(function () { setTimeout(CancelSelected, 1000); }, 100);
}

function CancelSelected() {
    alert("User selected stay/cancel");
}

Another variation
The first setTimeout waits for the user to respond to the browser's Leave/Cancel popup. The second setTimeout waits 1 second, and then CancelSelected is only called if the user cancels. Otherwise the page is unloaded and the setTimeout is lost.

window.onbeforeunload  = function(e) {
    e.returnValue = "message to user";
    setTimeout(function () { setTimeout(CancelSelected, 1000); }, 100);
}

function CancelSelected() {
    alert("User selected stay/cancel");
}
何以心动 2024-10-18 04:08:10
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
    }
 }

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

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.

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