歷史技巧(已失效/受限)
// 1. 傳統無提示關閉(僅限 window.open 開啟的視窗,且同源)
window.opener = null;
window.open("", "_self");
window.close();
// 2. 關閉當前頁(IE 會彈提示)
window.opener = null;
window.close();
現代瀏覽器安全限制
| 場景 | 能否關閉 | 說明 |
| 用戶直接輸入網址/書籤開啟 | ❌ | 瀏覽器禁止腳本關閉非腳本開啟的標籤頁 |
window.open() 開啟的彈出視窗 | ✅ | 同源下可 win.close(),跨域需 window.opener=null 後關閉 |
用戶點擊連結 target="_blank" | ❌ | 視為用戶主動開啟,腳本無權關閉 |
| PWA / 安裝型 Web App | ✅ | window.close() 正常運作 |
實用替代方案
1. 單頁應用(SPA)模擬關閉
function closeAppView() {
// 隱藏主內容,顯示「已關閉」頁面或登入頁
document.getElementById("app").style.display = "none";
document.getElementById("closedView").style.display = "flex";
history.replaceState(null, "", "/closed"); // 更新 URL 防止後退
}
2. 引導用戶手動關閉
function requestClose() {
if (confirm("操作已完成,請手動關閉此分頁。")) {
// 可嘗試關閉(若為彈出視窗會生效)
window.close();
}
}
3. beforeunload 確認離開(防誤關閉)
window.addEventListener("beforeunload", e => {
if (hasUnsavedChanges) {
e.preventDefault();
e.returnValue = "有未儲存的變更,確定要離開嗎?"; // 部分瀏覽器顯示
}
});
最佳實踐總結
- **不要承諾**能以程式碼關閉用戶主開的標籤頁。
- 彈出視窗流程:
const win = window.open(...) → 稍後 win.close()。
- SPA 內部「關閉」即為**路由跳轉/狀態重置**,非真正關閉視窗。
- 需用戶確認離開時,用
beforeunload,勿濫用。