首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JavaScript 跨雙層 iframe 修改孫頁面元素樣式

     編輯:程式設計疑難解答

場景

父頁面 → iframe 子頁面 → iframe 孫頁面。需在父頁面 JS 中修改孫頁面元素樣式。

核心原則:同源策略

**所有頁面必須同源** (協議、域名、埠相同),否則瀏覽器阻止跨框架訪問 DOM,拋出安全錯誤。

訪問鏈路

// 父頁面
var childFrame = document.getElementById('childIframe'); // 或 window.frames[0]
var grandChildFrame = childFrame.contentWindow.document.getElementById('grandChildIframe');
var targetElement = grandChildFrame.contentWindow.document.getElementById('targetId');
targetElement.style.color = 'red';

關鍵屬性

  • `iframeElement.contentWindow` → 獲取 iframe 內部 `window` 對象。
  • `iframeElement.contentDocument` (或 `contentWindow.document`) → 獲取 iframe 內部 `document`。

完整示例

<!-- 父頁面 -->
<iframe id="child" src="child.html"></iframe>
<script>
function modifyGrandChild() {
    try {
        var childWin = document.getElementById('child').contentWindow;
        var grandChildWin = childWin.document.getElementById('grandChild').contentWindow;
        var el = grandChildWin.document.getElementById('target');
        if (el) el.style.backgroundColor = 'yellow';
    } catch (e) {
        console.error('跨域或框架未就緒:', e);
    }
}
// 確保框架加載完成
window.addEventListener('load', modifyGrandChild);
</script>

異域解決方案

  • `postMessage` API:父頁面 `childWin.postMessage({type:'style', id:'target', style:{color:'red'}}, '*')`,孫頁面監聽 `message` 事件自行應用樣式。
  • `document.domain` 降級 (僅限主域相同,子域不同),現代瀏覽器已棄用/限制。

注意

  • iframe 載入是異步的,必須在 `onload` 後訪問內部 DOM。
  • 巢狀層級越深,維護越困難,建議扁平化架構或用 `postMessage` 解耦。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved