所有跨框架呼叫的前提是 同源(協定、域名、埠號完全相同)。跨域需用 postMessage,本文專注同源場景。
// 子頁面內
// 1. 呼叫父頁面全域函數
window.parent.parentFunction();
// 2. 存取父頁面 DOM 元素
const val = window.parent.document.getElementById('test').value;
// 3. jQuery 寫法(需父頁面也引入 jQuery)
const val = $(window.parent.document).find('#test').val();
// 父頁面內,iframe id="myFrame"
const iframe = document.getElementById('myFrame');
// 方式 A:contentWindow(標準,IE8+、所有現代瀏覽器)
iframe.contentWindow.childFunction();
// 方式 B:contentDocument(較少用)
iframe.contentDocument.defaultView.childFunction();
// 方式 C:舊 IE 專屬(不建議新專案用)
iframe.window.childFunction(); // 僅 IE
Chrome 5+ 安全機制:file:// 協定下 window.parent 存取會被阻擋,報錯 DOMException: Blocked a frame with origin "null"。
npx serve, python -m http.server, VS Code Live Server)改用 https://localhost 訪問。file:// 跨框架存取。<!DOCTYPE html>
<html lang="zh-Hant">
<head><meta charset="UTF-8"><title>父頁面</title></head>
<body>
<h2>父頁面</h2>
<input type="text" id="parentInput" value="父頁面資料">
<button onclick="callChild()">呼叫子頁面函數</button>
<iframe id="myFrame" src="child.html" width="100%" height="200"></iframe>
<script>
// 供子頁面呼叫
function parentFunc(msg) {
alert('父頁面收到:' + msg);
document.getElementById('parentInput').value = '已更新:' + msg;
}
// 呼叫子頁面
function callChild() {
const iframe = document.getElementById('myFrame');
// 確保 iframe 已載入
if (iframe.contentWindow && iframe.contentWindow.childFunc) {
iframe.contentWindow.childFunc('來自父頁面的問候 ' + Date.now());
} else {
console.warn('子頁面尚未就緒');
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="zh-Hant">
<head><meta charset="UTF-8"><title>子頁面</title></head>
<body style="background:#f9f9f9; padding:1rem;">
<h3>子頁面</h3>
<input type="text" id="childInput" value="子頁面資料">
<button onclick="callParent()">呼叫父頁面函數</button>
<script>
// 供父頁面呼叫
function childFunc(msg) {
alert('子頁面收到:' + msg);
document.getElementById('childInput').value = '已更新:' + msg;
}
// 呼叫父頁面
function callParent() {
try {
window.parent.parentFunc('來自子頁面的問候 ' + Date.now());
} catch (e) {
console.error('無法存取父頁面(跨域或 file:// 限制)', e);
}
}
</script>
</body>
</html>
postMessage 跨域通訊(簡介)// 父頁面
iframe.contentWindow.postMessage({type: 'CALL', fn: 'childFunc', args: ['hello']}, '*');
// 子頁面
window.addEventListener('message', e => {
if (e.data.type === 'CALL' && window[e.data.fn]) {
window[e.data.fn](...e.data.args);
}
});
詳細 postMessage 實作請參考 MDN 或另文說明。
| 錯誤現象 | 原因 | 解決 |
|---|---|---|
Cannot read property 'contentWindow' of null | iframe ID 錯誤或尚未渲染 | 確認 ID、放在 onload 後執行 |
Permission denied / Blocked a frame | 跨域或 file:// 協定 | 同源部署或用 postMessage |
| 子頁面函數未定義 | 腳本執行順序、拼字錯誤 | 在子頁面 window.onload 後再呼叫 |
window.parent.fn()iframe.contentWindow.fn()http(s):// 協定try-catch,避免中斷主流程