javascript加载前侦听器未正确启动



我有一个非常简单的html文件,其中包含一个包含beforeunload事件侦听器的javascript片段:

<!DOCTYPE html>
<html lang="en">
<body>
hello world
</body>
<script>
window.addEventListener("beforeunload", (event) => {
alert("hello");
});
</script>
</html>

根据mozilla的beforeunload文档,当我关闭选项卡时,我希望看到alert('hello')弹出。相反,选项卡关闭时没有发生任何其他事情。有人知道我做错了什么吗?谢谢

根据mozilla文档,对于chrome,还必须设置返回值。

<!DOCTYPE html>
<html lang="en">
<body>
hello world
</body>
<script>
window.addEventListener("beforeunload", (event) => {
event.preventDefault()
event.returnValue = '';
alert("hello");
});
</script>
</html>

你可能面临的问题是,一旦打开页面,你需要点击页面使其处于活动状态,然后一旦点击关闭选项卡,你应该得到";你确定";消息

尽管,即使在那时。。。警报不起作用。毫无疑问,这与文档顶部的小注释有关,它说这是为了防止烦人的弹出窗口。

最新更新