简体   繁体   English

在onbeforeunload()事件中使用Confirm()

[英]Using Confirm() in onbeforeunload() event

I want a confirm box to come up before unloading a page, and if the user clicks ok there a function needs to be called before leaving the page and if he clicks on cancel it should stay on the same page. 我想在卸载页面之前出现一个确认框,如果用户单击确定,则需要在离开页面之前调用一个函数,如果他点击取消它应该保持在同一页面上。

window.onbeforeunload = function() {
    if (!submitFormOkay) {
        if (confirm("Are you sure you want to leave?")) {
            leavepage();
        } else {
            submitfromokay = true;
            location.reload();
        }
    }
}

Is there anyway I can make this work using JS? 无论如何我可以使用JS来完成这项工作吗?

No, you can't. 不,你不能。 The only way to somehow accomplish that goal is by returning a String -value from your onbeforeunload handler. 以某种方式实现该目标的唯一方法是从onbeforeunload处理程序返回String onbeforeunload Some browsers ( Chrome for instance), will use that String and display it in their default warning message. 某些浏览器(例如Chrome )将使用该String并将其显示在默认警告消息中。 But other browsers, won't use it and just display a standard message, that gives the user a chance to interrupt the page unload. 但是其他浏览器不会使用它而只显示标准消息,这会让用户有机会中断页面​​卸载。

// Chrome will use the 'Y U LEAVING' string in its warning message now
window.onbeforeunload = function() {
    if(!submitFormOkay) {
        return 'Y U LEAVING ?';
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM