當父頁面顯式設定 document.domain 時,IE 系列瀏覽器會阻擋對同域但未同步設定 document.domain 的空白 iframe 進行 contentWindow.document.write 操作。本文深度解析「偽協議」 (javascript:) 繞過此限制的原理、風險與完整解決方案。
// 父頁面
document.domain = 'example.com'; // 顯式設定
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
// 嘗試動態寫入內容 (IE 報錯「拒絕存取」)
const doc = iframe.contentWindow.document;
doc.open();
doc.write('<h1>Hello</h1>');
doc.close();
// 關鍵:在設定 iframe.src 前,先將 覆寫
const base = document.querySelector('base') || document.createElement('base');
base.target = '_self';
if (!document.querySelector('base')) document.head.appendChild(base);
iframe.src = "javascript:void((function(){"
+ "var d=document;"
+ "d.open();"
+ "d.domain='example.com';" // 關鍵:同步設定 domain
+ "d.write('<h1>Hello</h1>');"
+ "d.close();"
+ "})())";
// 寫入完成後恢復 base target (若原本為 _blank)
base.target = '_blank';
同源策略要求「協定、域名、埠口」三者相同。設定 document.domain 可放寬至「父域名」同源。但 IE 要求**雙方皆顯式設定相同值**才允許互訪。空白 iframe 繼承的 document.domain 為 location.hostname,與父頁面顯式設定的 example.com 不符,導致拒絕存取。
iframe.src = "javascript:..." 會在 iframe 內建立一個**新的文檔上下文**。d.open() 後**立即設定 d.domain**,完成同步。d.write() 即在同源上下文中執行,不再受阻。<base target="_blank"> 導致新視窗彈出的 BugIE 另一 Bug:若父頁面有 <base target="_blank">,偽協議寫入的內容會在**新視窗**開啟而非 iframe 內。原因是 javascript: 導航被視為鏈接點擊,受 base target 影響。
**解決**:寫入前臨時將 base.target = '_self',寫入後恢復。
function writeIframeContent(iframe, html, domain) {
return new Promise((resolve, reject) => {
if (!iframe || !iframe.contentWindow) return reject('Invalid iframe');
// 處理 base target
let base = document.querySelector('base');
const hadBase = !!base;
if (!base) {
base = document.createElement('base');
document.head.appendChild(base);
}
const originalTarget = base.target;
base.target = '_self';
// 建構偽協議腳本
const script = `
(function() {
var d = document;
d.open();
${domain ? "d.domain='" + domain.replace(/'/g, "\\'") + "';" : ''}
d.write(${JSON.stringify(html)});
d.close();
})()
`;
// 監聽載入完成 (同步執行,但為保險)
const onLoad = () => {
cleanup();
resolve(iframe.contentWindow);
};
iframe.addEventListener('load', onLoad, { once: true });
// 設定 src 觸發
iframe.src = 'javascript:void(' + script + ')';
function cleanup() {
base.target = originalTarget;
if (!hadBase) base.remove();
iframe.removeEventListener('load', onLoad);
}
});
}
// 使用
writeIframeContent(iframe, '<h1>動態內容</h1>', 'example.com')
.then(win => console.log('寫入成功', win.document.title))
.catch(console.error);
| 風險 | 說明 | 緩解 |
|---|---|---|
| XSS 風險 | 動態構建腳本字串,若 html 來自不可信輸入 | 嚴格轉義、使用 JSON.stringify、CSP 限制 |
| 僅 IE 有效 | 現代瀏覽器 (Edge/Chrome/Firefox) 不需要此 Hack | UA 判斷僅 IE 執行,其他走標準 contentDocument.write |
| CSP 限制 | script-src 若無 'unsafe-inline' 可能阻擋 | 調整 CSP 或改用 srcdoc 屬性 (現代瀏覽器) |
| 歷史記錄污染 | 偽協議導航可能產生歷史記錄 | javascript:void(...) 通常不產生,但 IE 行為不一 |
iframe.srcdoc = '<h1>Hello</h1>'; 同源自動共享 domain。iframe.src = URL.createObjectURL(new Blob([html], {type:'text/html'})); 同源、無 domain 問題。偽協議方案是解決 **IE 歷史遺留跨域 document.domain 同步問題** 的經典 Hack。核心在於「偽協議建立新文檔上下文 → 立即同步 domain → 寫入內容」與「臨時覆寫 base target 防彈窗」。現代專案**強烈建議棄用 IE 支援**,改用 srcdoc 或 Blob URL,代碼更簡潔、安全、標準化。