<!-- 父頁面 -->
<iframe name="childFrame" id="childFrame" src="child.html"></iframe>
<button onclick="getChildValue()">獲取子頁面輸入值</button>
<script>
function getChildValue() {
var iframe = document.getElementById('childFrame');
// 方式 1:contentWindow(推薦)
var win = iframe.contentWindow;
var val = win.document.getElementById('date').value;
// 方式 2:contentDocument(標準)
// var val = iframe.contentDocument.getElementById('date').value;
// 方式 3:window.frames 集合(舊寫法)
// var val = window.frames['childFrame'].document.getElementById('date').value;
console.log('子頁面值:', val);
}
</script>
<input type="text" id="date" value="2024-01-15" />
同源策略禁止父頁面讀取跨域 iframe 內容。必須雙向協作:
<!-- child.html (不同域) -->
<script>
function sendData() {
var val = document.getElementById('date').value;
// 發送給父頁面,目標源建議指定具體域名而非 '*'
parent.postMessage({type: 'childData', value: val}, 'https://parent-domain.com');
}
// 數據變化時發送
document.getElementById('date').addEventListener('change', sendData);
// 頁面加載時發送
window.addEventListener('load', sendData);
</script>
<!-- 父頁面 -->
<script>
window.addEventListener('message', function(event) {
// 安全驗證來源
if (event.origin !== 'https://child-domain.com') return;
var data = event.data;
if (data && data.type === 'childData') {
console.log('收到子頁面值:', data.value);
// 更新 UI 或業務邏輯
}
}, false);
</script>
// 父頁面發送命令
iframe.contentWindow.postMessage({cmd: 'refresh'}, 'https://child-domain.com');
// 子頁面接收命令
window.addEventListener('message', function(e) {
if (e.origin !== 'https://parent-domain.com') return;
if (e.data.cmd === 'refresh') { /* 執行刷新 */ }
});
iframe.onload 後再訪問。contentWindow 仍可用,但文檔已換新;跨域跳轉後無法通訊。postMessage 推送聚合數據。qiankun、single-spa、Web Components。