window.onbeforeunload不显示警告框 [英] window.onbeforeunload not displaying the alert box

查看:474
本文介绍了window.onbeforeunload不显示警告框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想在离开页面之前显示一条消息,但我的代码不起作用:

I just want to show a message before leaving the page, but my code doesn't works:

window.onload=function(){
    alert("Page with a digital clock");
    setInterval(clock,1000);
}

window.onbeforeunload=function(){
    alert("Are you sure to leave this page?");
}

onload alert工作正常,但第二个不工作..

The "onload alert" works fine, but the second is not working..

推荐答案

您无法在onbeforeunload中添加警报。大多数浏览器都会为您执行此操作,因此您无需处理它,您需要将确认消息返回给该方法:

You can't put an alert inside onbeforeunload. Most browsers will do this for you so you don't need to handle it, you need to return the confirm message to the method instead:

window.onbeforeunload=function(){
    return "Are you sure to leave this page?";
}

以下是方法在MDN上


当此事件返回非void值时,系统会提示用户
确认页面卸载。在大多数浏览器中,
事件的返回值显示在此对话框中

When this event returns a non-void value, the user is prompted to confirm the page unload. In most browsers, the return value of the event is displayed in this dialog

这篇关于window.onbeforeunload不显示警告框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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