情境一:同一頁面多表單
<form name="form1"><input name="textfield"><button onclick="copy1to2()">1→2</button></form>
<form name="form2"><input name="textfield2"><button onclick="copy2to1()">2→1</button></form>
<script>
function copy1to2() { document.form2.textfield2.value = document.form1.textfield.value; }
function copy2to1() { document.form1.textfield.value = document.form2.textfield2.value; }
</script>
情境二:父視窗 ↔ 彈出視窗
// 父視窗開啟子視窗
var win = window.open('child.html', 'childWin', 'width=400,height=300');
// 子視窗寫入父視窗表單
// child.html 中:
function sendToParent(val) {
if (window.opener && !window.opener.closed) {
window.opener.document.form2.textfield2.value = val;
}
}
情境三:框架頁
<frameset cols="50%,50%">
<frame src="left.html" name="leftFrame">
<frame src="right.html" name="rightFrame">
</frameset>
// left.html 寫入 right.html 表單
function sendToRight(val) {
parent.rightFrame.document.form2.textfield2.value = val;
}
現代替代方案
- 同頁多表單:使用單一表單或狀態管理(Vue/React/Redux),避免跨表單存取。
- 跨視窗通訊:使用
window.postMessage(支援跨域、安全),取代 opener 直接操作 DOM。
- 跨框架/iframe:同源策略下可用
contentWindow.postMessage;跨域必須用 postMessage。
- SharedWorker / BroadcastChannel:同源多分頁/視窗共享狀態。
安全性提醒
- 直接操作
opener.document 或 parent.frame.document 受同源策略限制,跨域會報錯。
- 惡意子視窗可竄改父視窗表單,務必驗證來源
event.origin。