检查脚本打开的窗口是否关闭
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<button id="btn1">打开窗口</button>
<button id="btn2">检测</button>
<script src="./index.js"></script>
</body>
</html>
index.js
const btn1 = document.getElementById("btn1");
const btn2 = document.getElementById("btn2");
let targetWindow = null;
btn1.addEventListener("click", function () {
targetWindow = window.open("http://www.baidu.com");
});
btn2.addEventListener("click", function () {
if (targetWindow) {
if (targetWindow.closed) {
alert("窗口已经关闭");
} else {
alert("窗口还未关闭");
}
} else {
alert("窗口还未打开过");
}
});