父頁 ent.qq.com,iframe www.qq.com/coral/...,均屬 qq.com 主域。
// 父頁
document.domain = 'qq.com';
// iframe 內頁
document.domain = 'qq.com';
設置後,雙方視為同源,父頁可直接訪問 iframe.contentWindow.document.body.scrollHeight 並動態設置 iframe.style.height。
load 事件。document.domain = 'qq.com'。postMessage 獲取高度:// 父頁
iframe.onload = () => {
try {
iframe.contentDocument.domain = 'qq.com'; // 雙向設置
setInterval(() => {
const h = iframe.contentDocument.body.scrollHeight;
iframe.style.height = h + 'px';
}, 300);
} catch (e) { console.error('跨域失敗', e); }
};
// 父頁
window.addEventListener('message', e => {
if (e.origin !== 'https://www.qq.com') return;
if (e.data.type === 'resize') iframe.style.height = e.data.height + 'px';
});
// iframe 內頁
setInterval(() => {
parent.postMessage({type: 'resize', height: document.body.scrollHeight}, 'https://ent.qq.com');
}, 300);
| 方案 | 前提 | 優點 | 缺點 |
|---|---|---|---|
| document.domain | 同主域 | 代碼簡單、同步訪問 DOM | 無法跨主域、Chrome 80+ 棄用 |
| postMessage | 任意域 | 安全、標準、跨主域 | 異步、需雙方協議 |
document.domain。{type:'resize', height:123},驗證 e.origin 防注入。