萬盛學電腦網

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

JavaScript 修改 iframe 頁面背景色:跨文檔 DOM 操作與同源策略限制

修改嵌入 iframe 內容頁面的樣式,需訪問其 contentWindow 或 contentDocument,受同源策略嚴格限制:僅限同源(協議、域、端口相同)的 iframe。

核心代碼

function changeIframeBgColor(iframeId, color) {
  const iframe = document.getElementById(iframeId);
  // 兼容獲取內部 document
  const doc = iframe.contentDocument || iframe.contentWindow.document;
  
  if (doc && doc.body) {
    doc.body.style.backgroundColor = color;
  } else {
    console.error('無法訪問 iframe 文檔:跨域或未加載完成');
  }
}

// 用法
changeIframeBgColor('myframe', '#0000ff');

完整示例(同源環境下運行)

<!DOCTYPE html>
<html>
<head>
  <script>
    function changeStyle() {
      const iframe = document.getElementById('myframe');
      const doc = iframe.contentDocument || iframe.contentWindow.document;
      if (doc) doc.body.style.backgroundColor = '#0000ff';
    }
  </script>
</head>
<body>
  <iframe id="myframe" src="demo_iframe.htm"></iframe>
  <br><br>
  <button onclick="changeStyle()">修改背景色</button>
</body>
</html>

關鍵點詳解

  1. contentDocument:標準屬性,直接返回 iframe 的 Document 對象。
  2. contentWindow:返回 iframe 的 Window 對象,再取 .document。
  3. 加載時機:必須在 iframe.onload 後操作,否則文檔未就緒。
  4. 同源檢查:跨域訪問拋 SecurityError,控制台報錯。

跨域解決方案

方案原理適用場景
postMessage雙向消息通信,父頁發指令,子頁執行樣式修改跨域、可控制子頁代碼
document.domain設置相同主域(如 a.example.com / b.example.com → example.com)同主域不同子域(已棄用,現代瀏覽器限制)
CORS + 代理服務端代理轉發,使 iframe 頁面同源完全不可控的第三方頁面

postMessage 範例

// 父頁
iframe.contentWindow.postMessage({ type: 'SET_BG', color: '#f00' }, '*');

// 子頁
window.addEventListener('message', e => {
  if (e.data.type === 'SET_BG') document.body.style.backgroundColor = e.data.color;
});

總結

同源 iframe 可直接通過 contentDocument.body.style 修改樣式;跨域必須用 postMessage 協作。理解同源策略邊界,是前端安全開發的必修課。

copyright © 萬盛學電腦網 all rights reserved