window.onbeforeunload无法显示警告框

10

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

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" 工作得很好,但第二个没有起作用。
2个回答

17

你不能在 onbeforeunload 事件里放置 alert 。大多数浏览器会自动处理这个事件,所以你不需要手动处理它。相反,你需要将确认消息返回给该方法:

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

这里是MDN上有关 onbeforeunload 方法的文档

当该事件返回一个非 void 值时,用户将看到提示确认离开页面。在大多数浏览器中,该事件返回值将显示在此对话框中。


请参考 https://dev59.com/S3rZa4cB1Zd3GeqP4qDf#21456013 ,以便在 Firefox/IE 中实现此功能。 - jmcker

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接