萬盛學電腦網

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

JavaScript 視窗互傳值:showModalDialog 父子視窗通訊

showModalDialog 基本語法

var returnValue = window.showModalDialog(url, arguments, features);

父 → 子:傳遞參數

// parent.htm
var obj = { name: "justflyhigh.com", id: 123 };
window.showModalDialog("modal.htm", obj, "dialogWidth=400px;dialogHeight=300px;center=yes");

// modal.htm
var args = window.dialogArguments;
console.log(args.name); // "justflyhigh.com"
console.log(args.id);   // 123

子 → 父:回傳值

// parent.htm
var result = window.showModalDialog("modal.htm", null, "dialogWidth=200px;dialogHeight=100px");
console.log(result); // 接收回傳值

// modal.htm
window.returnValue = { status: "ok", data: "https://example.com" };
window.close(); // 關閉對話框,父視窗接收 returnValue

重要限制

  • Chrome 37+ / Edge / Firefox 已移除 showModalDialog
  • 僅 IE 與舊版 Safari 支援
  • 現代專案**不可使用**,需改用替代方案

現代替代方案

方案一:彈出視窗 + postMessage

// 父頁面
var win = window.open("modal.html", "_blank", "width=400,height=300");
window.addEventListener("message", function(e) {
    if (e.origin !== "https://trusted.com") return;
    console.log("收到子視窗資料:", e.data);
    win.close();
});

// 子頁面
window.opener.postMessage({ status: "ok", data: "..." }, "https://parent.com");

方案二:Modal 彈窗(同頁面)

// 使用 Bootstrap Modal、SweetAlert2、或自訂 Dialog 元件
// 資料透過 JS 變數/Props 直接傳遞,無跨視窗通訊問題

方案三:iframe + postMessage

嵌入 iframe,雙向 postMessage 通訊,相容性最佳。

copyright © 萬盛學電腦網 all rights reserved
參數說明
url對話框頁面網址(必填)
arguments傳遞給子視窗的參數(任意型別,含物件/陣列)
features視窗特性字串:dialogWidth/Height/Left/Top, center, help, resizable, status, scroll