gpt4 book ai didi

javascript - 如果未单击页面,为什么 onbeforeunload 不会触发?

转载 作者:行者123 更新时间:2023-12-03 01:31:00 24 4
gpt4 key购买 nike

我只是想知道这是为什么?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>close</title>
</head>
<body>
<h1>onbeforeunload</h1>

<script>
console.log("loaded");
window.onbeforeunload = confirmExit;
function confirmExit(){
console.log("closed");
return false;
}
</script>
</body>
</html>

如果您将此代码复制并保存为 .html 文件并在浏览器中运行它,并且不在页面内单击并关闭选项卡或浏览器,则 onbeforeunload 将不会触发!

但是,如果您在页面内单击一次,然后尝试关闭页面,则一切正常。

最佳答案

这是documented behaviour :

Note: To combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with; some don't display them at all. For a list of specific browsers, see the Browser_compatibility section.

关于javascript - 如果未单击页面,为什么 onbeforeunload 不会触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51304992/

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