`window.open()` 開啟新瀏覽器視窗或分頁,回傳新視窗的 `WindowProxy` 物件。掌握特性字串參數、同源策略限制、現代替代方案(`target="_blank"`、`rel="noopener"`、Dialog/Modal),避免彈窗攔截與安全風險。
基本語法
const newWin = window.open(url, target, features, replace);
| 參數 | 說明 |
| url | 載入網址,空字串則開啟空白頁 |
| target | 視窗名稱:`_blank`(新視窗)、`_self`(當前)、`_parent`、`_top`、或自訂名稱 (複用同名視窗) |
| features | 特性字串,逗號分隔,無空格:`width=800,height=600,left=100,top=100,scrollbars=yes,resizable=yes` |
| replace | Boolean,true 時以新 URL 取代歷史紀錄 (僅同源) |
常用特性字串鍵值
| 特性 | 值 | 說明 |
| width / height | 數字 | 視窗外部尺寸 (含工具列),最小值受瀏覽器限制 |
| left / top / screenX / screenY | 數字 | 視窗左上角螢幕座標 |
| noopener | yes/no | 新視窗 `opener` 為 null,防止反向存取、效能隔離 (現代瀏覽器 `target=_blank` 隱含) |
| noreferrer | yes/no | 不發送 Referer 標頭 |
| scrollbars / resizable / menubar / toolbar / location / status | yes/no/1/0 | UI 元件顯示,現代瀏覽器多忽略或強制顯示 |
回傳值與跨域通訊
const win = window.open('https://example.com', '_blank', 'width=600,height=400,noopener');
if (win) {
// 同源:可直接存取 win.document、呼叫函式
// 跨域:受同源策略限制,僅能 postMessage
win.postMessage({ type: 'init', data: '...' }, 'https://example.com');
} else {
alert('彈窗被攔截,請允許彈出視窗');
}
現代最佳實踐:避免 window.open
| 需求 | 推薦方案 | 優點 |
| 外部連結新分頁 | `` | 無 JS、無攔截、語意正確、SEO 友善 |
| OAuth/登入流程 | 彈窗 + `postMessage` 回傳 token | 安全、可控、行動裝置相容 |
| 複雜表單/精靈 | Modal/Dialog (ARIA role="dialog") | 同頁面、無攔截、無障礙、狀態共享簡單 |
| 列印/報表 | 新分頁 `window.open('', '_blank')` 寫入內容 + `print()` | 列印專用、可控制 CSS `@media print` |
彈窗攔截規則
- 必須在使用者互動事件(click、keydown、submit)中同步呼叫,異步(`setTimeout`、Promise `then`、AJAX 回調)會被攔截。
- 瀏覽器設定、擴充功能(uBlock、AdBlock)可能全域攔截。
- 行動裝置 Safari/Chrome 多視為新分頁而非獨立視窗,`features` 多數無效。
安全強化
// 開啟端
const win = window.open(url, '_blank', 'noopener,noreferrer');
// 目標頁 (同源或信任域) 可主動切斷關係
if (window.opener) { window.opener = null; }
`window.open` 仍有其特定用途(OAuth、列印、舊系統相容),但現代 Web 應優先採用連結、Modal、SPA 路由等非彈窗模式。