前言
window.open() 是開啟新視窗/分頁的標準 API。雖然現代瀏覽器預設攔截彈窗,但正確使用參數與使用者互動觸發 (click 事件內) 仍能可靠運作。本文完整列出所有參數、常見模式與最佳實踐。
語法
const newWindow = window.open(url, target, features, replace);
| 參數 | 類型 | 說明 |
| url | string | 要載入的 URL,空字串為 about:blank |
| target | string | 視窗名稱 (供 target 屬性/win.name 使用),_blank/_self/_parent/_top 或自訂名稱 |
| features | string | 逗號分隔的功能字串,控制視窗外觀與行為 |
| replace | boolean | true: 取代歷史紀錄 (不留回上頁),false: 預設新增紀錄 |
Features 完整參數表
| 參數 | 值 | 說明 | 備註 |
| width / innerWidth | 數值 | 視窗寬度 (px) | 最小值通常 100-200 |
| height / innerHeight | 數值 | 視窗高度 (px) | |
| left / screenX | 數值 | 距螢幕左緣距離 | |
| top / screenY | 數值 | 距螢幕上緣距離 | |
| toolbar | yes/no/1/0 | 工具列 | 現代瀏覽器多忽略 |
| menubar | yes/no | 選單列 | 現代瀏覽器多忽略 |
| location | yes/no | 網址列 | Chrome 強制顯示 |
| status | yes/no | 狀態列 | 已淘汰 |
| scrollbars | yes/no | 捲軸 | 建議 yes |
| resizable | yes/no | 可否調整大小 | 建議 yes |
| fullscreen | yes/no | 全螢幕 (IE/舊版) | 非標準 |
| noopener | yes/no | 新視窗 opener=null (安全) | **強烈建議加上** |
| noreferrer | yes/no | 不送 Referer header | 隱含 noopener |
實戰範例
1. 基本彈窗 (使用者點擊觸發)
function openPopup(url, name, w = 800, h = 600) {
const left = (screen.width - w) / 2;
const top = (screen.height - h) / 2;
const features = `width=${w},height=${h},left=${left},top=${top},scrollbars=yes,resizable=yes,noopener`;
return window.open(url, name, features);
}
// 綁定點擊 (必須在使用者互動事件中)
document.getElementById('btnOpen').addEventListener('click', () => {
openPopup('/detail.html', 'detailWin');
});
2. 表單提交至新視窗
<form action="/search" method="get" target="searchResult">
<input name="q"> <button type="submit">搜尋</button>
</form>
<script>
// 先開窗,再 submit (避免攔截)
document.querySelector('form').addEventListener('submit', function() {
window.open('', 'searchResult', 'width=1000,height=700,scrollbars=yes,resizable=yes,noopener');
this.target = 'searchResult'; // 確保 target 正確
});
</script>
3. 與子視窗雙向通訊
// 父頁面
const child = window.open('/child.html', 'childWin', 'width=600,height=400,noopener');
child.onload = () => {
// 父 → 子
child.postMessage({action: 'init', data: {userId: 123}}, '*');
};
// 子頁面
window.addEventListener('message', (e) => {
if (e.data.action === 'init') {
// 初始化
e.source.postMessage({action: 'ready'}, e.origin);
}
});
4. 關閉視窗與檢測是否被攔截
const win = window.open('/page', '_blank', 'noopener');
if (!win || win.closed || typeof win.closed === 'undefined') {
alert('彈窗被攔截,請允許彈出視窗');
} else {
// 正常開啟,可監聽關閉
const timer = setInterval(() => {
if (win.closed) { clearInterval(timer); console.log('子視窗已關閉'); }
}, 500);
}
安全性最佳實踐
- **永遠加上
noopener** (或 noreferrer),防止反向竊取 window.opener.location (Tabnabbing 攻擊)。
- **僅在使用者明確互動 (click/keydown) 內呼叫**,否則會被彈窗攔截器阻擋。
- **驗證 URL 來源**,避免開放重導向漏洞。
- **移動端體驗**:手機上彈窗即新分頁,建議改用原頁面導航或 Modal。
常見問題排查
| 現象 | 原因 | 解決 |
| window.open 回傳 null | 被瀏覽器攔截 | 改用 target=_blank 連結、或引導使用者允許彈窗 |
| features 不生效 | 瀏覽器忽略 (如 location, toolbar) | 接受無法完全控制,聚焦 width/height/left/top/scrollbars/resizable |
| 子視窗無法存取父頁 DOM | 跨域限制 | 同源才可直接存取,跨域用 postMessage |
| 關閉子視窗後父頁面重整 | 邏輯錯誤 | 檢查是否誤呼叫 opener.location.reload() |