当浏览器检测到非用户操作产生的新弹出窗口,则会对其进行阻止
场景:
1、非用户操作页面产生的跳转,如进入页面直接跳转
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function openLink () {
window.open("//www.baidu.com")
}
openLink()
</script>
</body>
</html>
2、尽管是用户操作页面产生的跳转,但产生了异步逻辑(我们项目中常见的就是ajax回调中使用跳转)(当等待时间小于5000毫秒时,不会拦截)例如点击事件中使用了定时器:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<button id="btn">click</button>
<body>
<script>
var btn = document.getElementById("btn")
btn.onclick = function () {
openLink()
}
function openLink () {
setInterval(() => {
window.open("//www.baidu.com")
}, 5000)
}
</script>
</body>
</html>
改善:
针对1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<button id="btn">click</button>
<body>
<script>
var btn = document.getElementById("btn")
btn.onclick = function () {
openLink()
}
function openLink () {
// setInterval(() => {
window.open("//www.baidu.com")
// }, 5000)
}
</script>
</body>
</html>
针对2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<button id="btn">click</button>
<body>
<script>
var btn = document.getElementById("btn")
btn.onclick = function () {
openLink()
}
function openLink () {
var win = window.open()
setInterval(() => {
win.location.href = "//www.baidu.com"
}, 5000)
}
</script>
</body>
</html>
这种方案会导致等待五秒的空白页面时间,因此不太适合长时间等待回调的场景。
针对这种场景,我们可以在异步回调执行后,弹出一个弹窗让用户点击后在执行跳转,将其转化为用户操作引起的同步跳转