萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript window.open() 完整參數指南與實戰範例

前言

window.open() 是開啟新視窗/分頁的標準 API。雖然現代瀏覽器預設攔截彈窗,但正確使用參數與使用者互動觸發 (click 事件內) 仍能可靠運作。本文完整列出所有參數、常見模式與最佳實踐。

語法

const newWindow = window.open(url, target, features, replace);
參數類型說明
urlstring要載入的 URL,空字串為 about:blank
targetstring視窗名稱 (供 target 屬性/win.name 使用),_blank/_self/_parent/_top 或自訂名稱
featuresstring逗號分隔的功能字串,控制視窗外觀與行為
replacebooleantrue: 取代歷史紀錄 (不留回上頁),false: 預設新增紀錄

Features 完整參數表

參數值說明備註
width / innerWidth數值視窗寬度 (px)最小值通常 100-200
height / innerHeight數值視窗高度 (px)
left / screenX數值距螢幕左緣距離
top / screenY數值距螢幕上緣距離
toolbaryes/no/1/0工具列現代瀏覽器多忽略
menubaryes/no選單列現代瀏覽器多忽略
locationyes/no網址列Chrome 強制顯示
statusyes/no狀態列已淘汰
scrollbarsyes/no捲軸建議 yes
resizableyes/no可否調整大小建議 yes
fullscreenyes/no全螢幕 (IE/舊版)非標準
noopeneryes/no新視窗 opener=null (安全)**強烈建議加上**
noreferreryes/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);
}

安全性最佳實踐

  1. **永遠加上 noopener** (或 noreferrer),防止反向竊取 window.opener.location (Tabnabbing 攻擊)。
  2. **僅在使用者明確互動 (click/keydown) 內呼叫**,否則會被彈窗攔截器阻擋。
  3. **驗證 URL 來源**,避免開放重導向漏洞。
  4. **移動端體驗**:手機上彈窗即新分頁,建議改用原頁面導航或 Modal。

常見問題排查

現象原因解決
window.open 回傳 null被瀏覽器攔截改用 target=_blank 連結、或引導使用者允許彈窗
features 不生效瀏覽器忽略 (如 location, toolbar)接受無法完全控制,聚焦 width/height/left/top/scrollbars/resizable
子視窗無法存取父頁 DOM跨域限制同源才可直接存取,跨域用 postMessage
關閉子視窗後父頁面重整邏輯錯誤檢查是否誤呼叫 opener.location.reload()
copyright © 萬盛學電腦網 all rights reserved