在写一个需求,要求用户进入页面,返回/刷新/关闭该页面提示用户一些信息。发现在使用window.onbeforeunload的时候,必须打开调试才会生效,而且只有第一次有效,再次点击就会失效。
在实际使用中让用户打开调试模式肯定是不可能的,后来发现出现这种情况是因为没有在该页面有任何操作,或者是操作时间间隔太短,所以不会有提示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="format-detection" content="telephone=no,email=no,adress=no" />
</head>
<body>
<input type="text">
</body>
<script>
//方法一
window.onbeforeunload = function(){
return '真的要关闭此窗口吗?';
}
//or 方法二
window.addEventListener("beforeunload", function(event) {
//event.preventDefault();
event.returnValue = "真的要关闭此窗口吗?";
});
</script>
</html>
打开该页面后,在该页面没有任何操作,不会有提示,在input中输入文字或者其他信息,刷新/返回/关闭该页面都会有提示;刷新/返回/关闭操作时间间隔太短有时有提示,有时没有。
所以只有在该页面有操作,并且时间间隔大于5秒左右即会有提示。
在vue中放到mounted里面
本文转自 https://blog.csdn.net/qq_35310623/article/details/115324956,如有侵权,请联系删除。