DIV CSS 佈局教程網

JavaScript window 物件全解析:開窗、關窗、跨視窗傳值
編輯:JavaScript綜合知識     

window 是瀏覽器物件模型(BOM)中的頂層物件,所有全域變數、全域函數與內建物件都掛在它上面。以下依實用性整理它最常被用到的方法與跨視窗溝通技巧。

一、開啟新視窗:window.open

window.open(pageURL, name, parameters)
  • pageURL:子視窗的路徑
  • name:子視窗的名稱/句柄
  • parameters:視窗參數,各項以逗號分隔
window.open("https://www.example.com/", "open",
    'height=100,width=400,top=0,left=0,toolbar=no,menubar=no,' +
    'scrollbars=no,resizable=no,location=no,status=no');

注意:現代瀏覽器基於安全考量,網址列與狀態列通常無法隱藏,且除了 width/height 以外的參數多半會被忽略。此外,非由使用者操作直接觸發的 window.open 會被 Popup Blocker 攔下。

二、模式視窗:showModalDialog

window.showModalDialog("https://www.example.com/", "open",
    "toolbars=0;width=200;height=200");

它會開啟一個無法與母視窗互動的強制回應視窗,且會回傳子視窗的 returnValue,因此早期常用來做表單回傳。但這支 API 已被標準廢棄(MDN 標示 deprecated),Chrome 與 Firefox 均已移除,新專案請勿使用。

三、關閉視窗而不跳確認框

若網頁不是由 window.open() 開啟的,IE7/IE8 在執行 window.close() 時會跳出「是否關閉」的確認框。解法是先把 opener 設為 null:

<script>
function closeWindow() {
    window.opener = null;
    window.open('', '_self', '');
    window.close();
}
</script>
<input type="button" value="關閉視窗" onClick="closeWindow()" />

若是要關閉框架集視窗:

function closeWindow() {
    window.opener = null;
    window.open('', '_top', '');
    window.parent.close();
}

現代瀏覽器只允許關閉由腳本開啟的視窗,其他情況 close() 會被靜默忽略——這是刻意的安全設計。

四、location 物件

window.location.reload();                       // 重新整理
window.location.href = "https://www.example.com/"; // 載入其他頁面

五、history 物件

window.history.go(1);    // 前進
window.history.go(-1);   // 後退

六、父子視窗互相傳值

寫法 A:用 returnValue 回傳(showModalDialog)

// 父視窗
var str = window.showModalDialog("s.html");
if (str != null) {
    document.getElementById("v").value += str;
}

// 子視窗
var v = document.getElementById("v");
window.returnValue = v.value;
window.close();

主視窗端接收:

function openWindow() {
    var bankCard = window.showModalDialog("counter.html", "",
        "dialogWidth=400px;dialogHeight=200px");
    alert("您的資訊是:" + bankCard);
}

寫法 B:用 dialogArguments 傳入(showModalDialog)

// 父視窗:把 window 本身當參數傳進去
function opendialog() {
    window.showModalDialog("child.html", window, "resizable=false");
}

// 子視窗:用 dialogArguments 取回並直接操作父視窗
function updateParent() {
    var pwin = window.dialogArguments;
    if (pwin != undefined) {
        pwin.document.getElementById("name").value =
            document.getElementById("name").value;
    }
}

寫法 C:用 window.opener(window.open,推薦)

這是目前仍然有效的標準做法。window.open() 開啟的子視窗,可以透過 window.opener 取得父視窗參照:

// 父視窗 FatherPage.htm
function OpenChildWindow() {
    window.open('ChildPage.htm');
}
// 子視窗 ChildPage.htm
function SetValue() {
    window.opener.document.getElementById('txtInput').value =
        document.getElementById('txtInput').value;
    window.close();
}

反過來,window.open() 本身會回傳子視窗的參照,因此父視窗也能在開啟當下就對子視窗賦值:

function OpenChildWindow() {
    var child = window.open('ChildPage.htm');
    child.document.getElementById('txtInput').value =
        document.getElementById('txtInput').value;
}

利用這個參照做非空判斷,可以限制只能開一個子視窗:

var child;
function OpenChildWindow() {
    if (!child || child.closed) child = window.open('ChildPage.htm');
    child.document.getElementById('txtInput').value =
        document.getElementById('txtInput').value;
}

但這樣還不夠——子視窗關閉時必須把父視窗的變數清空,否則第二次點擊會因為參照已失效而無法再開:

<body onunload="Unload()">
<script>
function SetValue() {
    window.opener.document.getElementById('txtInput').value =
        document.getElementById('txtInput').value;
    window.close();
}
function Unload() {
    window.opener.child = null;   // 清空父視窗的參照
}
</script></body>

實務上更乾淨的判斷是 if (!child || child.closed),不必依賴子視窗反向清空父視窗的變數。

現代替代方案

  • 同來源情境用 localStorage + storage 事件,或直接用上面示範的 opener/window.open 回傳參照。
  • 跨來源情境必須用 postMessage()。直接跨來源讀寫 opener.document 會被同源政策阻擋,且永遠不要在接收端省略 event.origin 的檢查,否則等於開放任意網站對你的頁面下指令。
  • 視窗之間共享狀態可用 BroadcastChannel,比輪詢 localStorage 更直觀。
  • 對話框請用 <dialog> + showModal(),它是標準元素,具備焦點鎖定、Esc 關閉與無障礙支援,完全不需要開新視窗。
  • showModalDialog 已從標準移除,請勿在新專案使用。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved