gpt4 book ai didi

javascript - 如何覆盖 OnBeforeUnload 对话框并将其替换为我自己的?

转载 作者:行者123 更新时间:2023-11-28 02:45:46 26 4
gpt4 key购买 nike

我需要在用户离开页面之前就未保存的更改发出警告(这是一个很常见的问题)。

window.onbeforeunload = handler

这行得通,但它会引发一个默认对话框,其中包含一条包含我自己的文本的烦人的标准消息。我需要完全替换标准消息,以便我的文本清晰,或者(甚至更好)使用 jQuery 将整个对话框替换为模态对话框。

到目前为止,我都失败了,而且我还没有找到其他人似乎有答案。有可能吗?

我页面中的 Javascript:

<script type="text/javascript">   
window.onbeforeunload = closeIt;
</script>

closeIt() 函数:

function closeIt()
{
if (changes == "true" || files == "true")
{
return "Here you can append a custom message to the default dialog.";
}
}

使用 jQuery 和 jqModal 我已经尝试过这种事情(使用自定义确认对话框):

$(window).beforeunload(function () {
confirm('new message: ' + this.href + ' !', this.href);
return false;
});

这也不起作用 - 我似乎无法绑定(bind)到 beforeunload 事件。

最佳答案

您无法修改 onbeforeunload 的默认对话,因此您最好的选择可能是使用它。

window.onbeforeunload = function() {
return 'You have unsaved changes!';
}

Here's a reference对此来自微软:

When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.

问题似乎是:

  1. 当调用onbeforeunload时,它会将处理程序的返回值作为window.event.returnValue
  2. 然后它将返回值解析为字符串(除非它为空)。
  3. 由于 false 被解析为字符串,对话框将触发,然后传递适当的 true/false。<

结果是,似乎没有办法将 false 分配给 onbeforeunload 以防止它进入默认对话。

关于 jQuery 的补充说明:

  • 在 jQuery 中设置事件可能是有问题的,因为这也允许其他onbeforeunload 事件发生。如果您只希望发生卸载事件,我会坚持使用普通的 JavaScript。
  • jQuery 没有 onbeforeunload 的快捷方式,因此您必须使用通用的 bind 语法。

    $(window).bind('beforeunload', function() {} );

编辑 09/04/2018:onbeforeunload 对话框中的自定义消息自 chrome-51 以来已弃用(参见:release note)

关于javascript - 如何覆盖 OnBeforeUnload 对话框并将其替换为我自己的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41630032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com