window.onbeforeunload不显示警告框

时间:2013-11-19 09:17:17

标签: javascript onbeforeunload

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

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”工作正常,但第二个不起作用..

1 个答案:

答案 0 :(得分:10)

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

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

以下是方法on MDN的文档。

  

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