window.open() 的第二個參數 windowName 不只是視窗標題,更是視窗標識符。IE7+、現代瀏覽器嚴格遵循:相同 name 會復用現有視窗,導致「無法開啟多個獨立彈窗」、「父子視窗通訊混亂」等問題。本文深度解析 name 機制、跨域通訊影響與解決方案。
const win = window.open(url, name, features);
name (第二參數):瀏覽上下文名稱,對應 HTML 標準的 browsing context name_blank (新視窗)、_self (當前)、_parent、_top// ❌ 錯誤:全部用同一 name
window.open('page1.html', 'popup', 'width=400,height=300');
window.open('page2.html', 'popup', 'width=400,height=300'); // 覆蓋 page1!
// ✅ 正確:使用唯一 name
window.open('page1.html', 'popup_1', 'width=400,height=300');
window.open('page2.html', 'popup_2', 'width=400,height=300');
// 父頁面
const child = window.open('child.html', 'sharedName');
child.postMessage({type: 'init'}, '*'); // 可能發送給錯誤視窗!
// 子頁面
window.opener.postMessage({type: 'ready'}, '*'); // opener 可能被覆蓋
若多個彈窗共用 name,window.open 返回的引用可能指向舊視窗,導致 postMessage 發送錯誤、opener 指向錯誤。
若多個第三方 SDK 都用 window.open(url, 'oauth'),會互相覆蓋 OAuth 視窗,導致登入流程中斷。
function openUniqueWindow(url, features = '') {
const name = `win_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
return window.open(url, name, features);
}
// 使用
const win1 = openUniqueWindow('page1.html', 'width=400,height=300');
const win2 = openUniqueWindow('page2.html', 'width=400,height=300');
const windows = new Map();
function openTrackedWindow(url, key, features = '') {
const win = window.open(url, '_blank', features);
if (win) {
windows.set(key, win);
// 監聽關閉清理
const checkClosed = setInterval(() => {
if (win.closed) {
clearInterval(checkClosed);
windows.delete(key);
}
}, 500);
}
return win;
}
// 使用
openTrackedWindow('page1.html', 'dashboard');
openTrackedWindow('page2.html', 'settings');
// 後續通訊
windows.get('dashboard')?.postMessage({type: 'update'}, '*');
let sharedPopup = null;
function openSharedPopup(url, features = '') {
if (sharedPopup && !sharedPopup.closed) {
sharedPopup.focus(); // 聚焦現有
sharedPopup.location.href = url; // 更新 URL
return sharedPopup;
}
sharedPopup = window.open(url, 'shared_popup', features);
return sharedPopup;
}
// 父頁面
const child = window.open('https://child.example.com', 'unique_name');
child.postMessage({type: 'init', data: '...'}, 'https://child.example.com'); // 指定 targetOrigin!
// 子頁面
window.addEventListener('message', (event) => {
if (event.origin !== 'https://parent.example.com') return; // 驗證來源!
if (event.data.type === 'init') {
event.source.postMessage({type: 'ready'}, event.origin);
}
});
| 維度 | window.open 彈窗 | 模態框 (Dialog/Modal) |
|---|---|---|
| 瀏覽器攔截 | 高 (需用戶手势觸發) | 無 |
| 跨域隔離 | 完全隔離 (安全) | 同源 (共享狀態) |
| 行動裝置體驗 | 差 (新分頁/覆蓋) | 優 |
| 狀態共享 | 需 postMessage | 直接共享 JS 狀態 |
| 適用場景 | OAuth、支付、列印、跨域嵌入 | 表單、確認、複雜互動 |
windowName 是瀏覽上下文身份證,非裝飾性標題_blank + 引用管理event.origin、指定 targetOrigin這個「name 參數」的小細節,是前端工程師從「能跑通」邁向「健壯架構」的分水嶺之一。