监听子窗口的聚焦与失焦
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<button onclick="clickHandler()">open: sub.html</button>
<script>
// 测试父窗口是否能监听聚焦和失焦,结果发现是可以的。
window.onfocus = function (e) {
console.log(e); // 每次聚焦都打印出事件参数
};
window.onblur = function (e) {
console.log(e); // 每次失焦都打印出事件参数
}
function clickHandler() {
const newWindow = window.open(
"./sub.html",
"_blank",
"left=0,top=0,height=500,width=800"
);
setTimeout(function () {
newWindow.focus(); // 自动在 3s 后聚焦,表现为不在焦点的子窗口自动出现在屏幕最上层
}, 3000);
}
</script>
</body>
</html>
sub.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<script>
window.onfocus = function (e) {
console.log(e); // 每次聚焦都打印出事件参数
};
window.onblur = function (e) {
console.log(e); // 每次失焦都打印出事件参数
};
</script>
</body>
</html>