本文整理 JavaScript 中父子視窗互相取用變數與函式的兩種典型場景,並附可運行的範例。
父視窗:
<!DOCTYPE html>
<html>
<head>
<title>parent</title>
<script type="text/javascript">
var parentPara = 'parent';
function parentFunction() {
alert(parentPara);
}
</script>
</head>
<body>
<button onclick="parentFunction()">顯示變數值</button>
<button onclick="window.open('child.html')">打開新視窗</button>
</body>
</html>
子視窗:
<!DOCTYPE html>
<html>
<head>
<title>child</title>
<script type="text/javascript">
function modify() {
opener.parentPara = 'child';
}
</script>
</head>
<body>
<button onclick="opener.parentFunction()">呼叫父頁面的方法</button>
<button onclick="modify()">更改父頁面中變數的值</button>
</body>
</html>
關鍵就是 opener:它指向開啟這個視窗的那個 window 物件,在前面加上它就能存取父視窗的變數與函式。
要注意的是,若父視窗已經被關閉,再這樣呼叫會拋出「被呼叫的物件已與其客戶端中斷連線」這類錯誤。實務上應該先做防禦:
function safeCall(fn) {
if (window.opener && !window.opener.closed && typeof window.opener[fn] === 'function') {
window.opener[fn]();
}
}
父頁面:
<!DOCTYPE html>
<html>
<head>
<title>parent</title>
<script type="text/javascript">
function fill() {
// 讀取 iframe 內的變數值
// alert(frame1.window.childPara);
var str = document.getElementById('txt1').value;
// 把值填進子頁面的一個 div
frame1.window.div1.innerHTML = str;
}
</script>
</head>
<body>
<div style="background-color:yellow;width:300px;height:300px;">
父頁面
<iframe id="frame1" src="child.html" frameborder="0" width="120px" height="120px"></iframe>
<br/><br/><br/><br/>
<input id="txt1" type="text"/>
<button onclick="fill()">將輸入框的值填入子頁面</button>
</div>
</body>
</html>
子頁面:
<!DOCTYPE html>
<html>
<head>
<title>child</title>
<script type="text/javascript">
function fun() {
parent.fill();
}
</script>
</head>
<body>
<div style="background-color:lightblue;width:100px;height:100px;">
<b>子頁面</b><br/>
<a href="#" onclick="fun()">同父頁面按鈕</a>
<div id="div1" style="color:red;"></div>
</div>
</body>
</html>
在 iframe 內,parent 就是父視窗的 window 物件;若要明確指定,也可以用具名的 window.frames['frame1']。多層嵌套時,top 會一路指向最外層。
順帶記錄一個觀察:重新整理父頁面時,其中的 iframe 也會跟著重載;但只刷新 iframe 時,父頁面不會受影響。
1. 同源政策。 如果 iframe 指向不同網域,跨視窗存取會直接拋出安全性錯誤。跨網域溝通請改用 postMessage,並務必在 message 事件中檢驗 event.origin,不要來信就照辦。
2. 時序問題。 父頁面在 iframe 尚未載入完成時就存取 frame1.window.div1,會得到 undefined。應該監聽 iframe 的 load 事件,或從子頁面主動通知父頁面「我好了」。
3. 直接操作子頁面的 DOM 很脆弱。 範例中 frame1.window.div1 這種寫法把父子結構綁死了。較好的做法是父頁面只呼叫子頁面暴露的函式,讓 DOM 細節留在子頁面自己家裡。
4. opener 的資安風險。 用 window.open 開啟外部連結時,被開啟的頁面可以透過 opener 反向操作你的頁面(tabnabbing)。開外站請加上 noopener,或直接寫 <a target="_blank" rel="noopener noreferrer">。
希望本文所述對大家的 JavaScript 設計有所幫助。