修改嵌入 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>
.document。iframe.onload 後操作,否則文檔未就緒。SecurityError,控制台報錯。| 方案 | 原理 | 適用場景 |
|---|---|---|
| postMessage | 雙向消息通信,父頁發指令,子頁執行樣式修改 | 跨域、可控制子頁代碼 |
| document.domain | 設置相同主域(如 a.example.com / b.example.com → example.com) | 同主域不同子域(已棄用,現代瀏覽器限制) |
| CORS + 代理 | 服務端代理轉發,使 iframe 頁面同源 | 完全不可控的第三方頁面 |
// 父頁
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 協作。理解同源策略邊界,是前端安全開發的必修課。