新視窗與子視窗之間如何傳遞資料,是前端相當古典卻仍常遇到的問題。以下把兩種主要途徑的參數與用法整理清楚。
支援環境:JavaScript 1.0+ / JScript 1.0+ / Navigator 2+ / IE3+ / Opera3+
window.open(pageURL, name, parameters) pageURL 子視窗的路徑 name 彈出視窗的名稱 parameters 視窗參數,各項以逗號分隔
alwaysLowered / alwaysRaised:視窗永遠在後/永遠在前depended:是否與父視窗同時關閉directories:目錄列是否顯示height / width:視窗像素高度與寬度hotkeys:無選單視窗是否啟用安全退出熱鍵innerHeight / innerWidth:視窗內文件的像素尺寸outerHeight / outerWidth:含邊框的整體尺寸location:網址列是否顯示menubar / toolbar / titlebar / scrollbars / status:各項介面元素是否顯示resizable:是否可調整大小screenX / screenY:距螢幕左/上邊界的距離z-lock:啟動後是否浮在其他視窗之上<SCRIPT>
window.open('page.html', 'newwindow',
'height=100,width=400,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
</SCRIPT>
vReturnValue = window.showModalDialog(sURL [, vArguments] [, sFeatures]) vReturnValue = window.showModelessDialog(sURL [, vArguments] [, sFeatures])
sURL 為必填,指定要顯示的文件網址。vArguments 用來向對話框傳遞參數,型別不限,陣列或物件都可以,對話框內透過 window.dialogArguments 取得。sFeatures 則描述外觀,多項以分號隔開。
dialogHeight / dialogWidth:對話框尺寸,高度不小於 100pxdialogLeft / dialogTop:距螢幕左/上的距離center:是否置中,預設 yeshelp:是否顯示說明按鈕resizable:是否可縮放,預設 nostatus:是否顯示狀態列scroll:是否顯示捲軸dialogHide / edge / unadorned:HTA 專用,一般網頁不會用到// parent.htm
<script>
var obj = new Object();
obj.name = "51js";
window.showModalDialog("modal.htm", obj, "dialogWidth=200px;dialogHeight=100px");
</script>
// modal.htm
<script>
var obj = window.dialogArguments;
alert("您傳遞的參數為:" + obj.name);
</script>
// parent.htm
<script>
var str = window.showModalDialog("modal.htm", null, "dialogWidth=200px;dialogHeight=100px");
alert(str);
</script>
// modal.htm
<script>
window.returnValue = "https://www.example.com";
</script>
window.location.href = "目標頁面"; // 於原視窗跳轉
window.open('目標頁面'); // 於新視窗開啟
window.history.back(-1); // 返回上一頁
showModalDialog 屬 IE 專屬 API,其他瀏覽器從未支援,如今已不建議使用;跨瀏覽器要傳值,直接用 window.open 開視窗後以 opener/postMessage 溝通,或乾脆改用頁內的 modal 彈出層,會是更長遠的方案。