萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 與 jQuery 跨 Iframe 存取父/子視窗元素完整指南

同源策略前提

**所有跨框架存取要求同源**(協定、域名、埠號相同)。跨域需使用 postMessage 通訊,本文專注同源場景。

原生 JavaScript 方案

父頁面 → 存取 Iframe 內部


// 方法 1:iframe element.contentWindow
var iframe = document.getElementById('myIframe');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var btn = innerDoc.getElementById('btnOk');
btn.click();

// 方法 2:window.frames 集合 (需 iframe 有 name 屬性)
window.frames['iframeName'].document.getElementById('btnOk').click();

// 方法 3:iframe element.contentWindow 直接呼叫函式
iframe.contentWindow.someFunctionInIframe();

Iframe 內部 → 存取父頁面


// 直接存取父文件
window.parent.document.getElementById('btnOk').click();

// 呼叫父頁面函式
window.parent.parentFunction();

// 存取頂層視窗 (穿透多層巢狀)
window.top.document.getElementById('globalHeader').style.display = 'none';
window.top.globalFunction();

jQuery 方案 (更簡潔)

父頁面 → Iframe


// 方法 1:contents() + find() (推薦)
$('#myIframe').contents().find('#btnOk').click();

// 方法 2:指定 context
$('#btnOk', document.frames['iframeName'].document).click();
// 或
$('#btnOk', $('#myIframe')[0].contentWindow.document).click();

Iframe → 父頁面


// 選擇器 + context 參數
$('#btnOk', parent.document).click();

// 呼叫父頁面函式
parent.parentFunction();

// 存取頂層
$('#globalHeader', top.document).hide();

完整互動範例

父頁面 (parent.html)


<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>父頁面</title>
    <script src="jquery.min.js"></script>
</head>
<body>
    <h2>父頁面</h2>
    <button id="parentBtn">父頁面按鈕</button>
    <div id="parentMsg">等待子頁面訊息...</div>
    
    <iframe id="childFrame" src="child.html" style="width:100%;height:300px;border:1px solid #ccc"></iframe>
    
    <script>
        // 父頁面提供給子頁面呼叫的函式
        window.receiveFromChild = function(msg) {
            $('#parentMsg').text('收到子頁面: ' + msg).css('color', 'green');
        };
        
        // 父頁面主動操作子頁面 (需等 iframe 載入完成)
        $('#childFrame').on('load', function() {
            // 修改子頁面標題
            $(this).contents().find('h2').text('子頁面 (已被父頁面修改)');
            
            // 綁定子頁面按鈕事件
            $(this).contents().find('#childBtn').on('click', function() {
                alert('父頁面捕獲到子頁面按鈕點擊!');
            });
        });
        
        // 父頁面按鈕觸發子頁面函式
        $('#parentBtn').click(function() {
            var iframeWin = document.getElementById('childFrame').contentWindow;
            if (iframeWin.childFunction) {
                iframeWin.childFunction('來自父頁面的問候');
            }
        });
    </script>
</body>
</html>

子頁面 (child.html)


<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>子頁面</title>
    <script src="jquery.min.js"></script>
</head>
<body>
    <h2>子頁面</h2>
    <button id="childBtn">子頁面按鈕</button>
    <div id="childMsg">等待父頁面訊息...</div>
    
    <script>
        // 子頁面提供給父頁面呼叫的函式
        window.childFunction = function(msg) {
            $('#childMsg').text('收到父頁面: ' + msg).css('color', 'blue');
        };
        
        // 子頁面主動操作父頁面
        $('#childBtn').click(function() {
            // 方式 1:直接呼叫父頁面函式
            parent.receiveFromChild('子頁面主動發送');
            
            // 方式 2:jQuery 操作父頁面 DOM
            $('#parentMsg', parent.document).text('子頁面直接修改 DOM').css('color', 'orange');
        });
    </script>
</body>
</html>

常見坑點與解決

問題原因解決
Permission denied / 拒絕存取跨域 (不同源)改用 postMessage、CORS、代理
contentDocument 為 nulliframe 尚未載入完成綁定 iframe.onload 後再操作
找不到元素選擇器錯誤、iframe 內容動態載入用 .find() 搭配完整選擇器、等待元素就緒
多層巢狀 iframeparent/parent.parent 混淆用 window.top 定位頂層、命名 iframe 便於識別

跨域解決方案:postMessage


// 父頁面
window.addEventListener('message', function(e) {
    if (e.origin !== 'https://child-domain.com') return; // 驗證來源
    if (e.data.type === 'childReady') {
        console.log('子頁面準備好:', e.data.payload);
    }
});

// 子頁面
window.parent.postMessage({ 
    type: 'childReady', 
    payload: { userId: 123 } 
}, 'https://parent-domain.com'); // 指定目標 origin,安全

現代架構建議

  • 避免 Iframe:採用 SPA 架構、Web Components、Micro-frontends
  • 必要時隔離:第三方嵌入 (支付、地圖、編輯器) 用 `