萬盛學電腦網

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

JavaScript document.domain 跨域核心原理與實戰注意事項

前言

document.domain 是瀏覽器同源策略 (Same-Origin Policy) 中少數可「放寬」的機制,允許**同一基礎域名**下的不同子域名頁面互相訪問 DOM/JS 物件。本文深入解析其運作原理、設定規則、實戰坑點、以及現代替代方案。

核心規則:只能設定為「基礎域名」或「當前域名」


// 假設當前頁面:https://www.example.com/page.html

document.domain = 'example.com';    // ✅ 成功:基礎域名 (Base Domain)
document.domain = 'www.example.com'; // ✅ 成功:當前完整域名
document.domain = 'com';             // ❌ 失效:公共後綴 (Public Suffix) 禁止
document.domain = 'other.com';       // ❌ 失效:非同源基礎域名
document.domain = 'sub.example.com'; // ❌ 失效:非當前域名也非基礎域名

什麼是基礎域名?

由**公共後綴列表 (Public Suffix List)** 定義。例如:

  • www.example.com → 基礎域名 example.com
  • a.b.example.co.uk → 基礎域名 example.co.uk (非 co.uk)
  • github.io → 基礎域名 github.io (在 PSL 中)

瀏覽器內建 PSL,防止 co.uk、github.io 等被設為 document.domain 導致跨站洩露。

實現跨子域通訊流程

場景

  • 頁面 A:https://app.example.com/page-a.html
  • 頁面 B (iframe 嵌入):https://api.example.com/widget.html

雙方都必須設定


// 頁面 A (主頁)
document.domain = 'example.com';

// 頁面 B (iframe 內容) - **必須在腳本最開頭執行**
document.domain = 'example.com';

// 之後即可互相訪問
// 頁面 A 中:
const iframeWin = document.getElementById('my-iframe').contentWindow;
iframeWin.someFunction(); // 可呼叫 iframe 內函式
console.log(iframeWin.document.title); // 可讀取 iframe DOM

// 頁面 B 中:
parent.someGlobalFunction(); // 可呼叫父頁面函式

關鍵限制與坑點 (必讀!)

限制說明影響
協議必須相同 HTTP ↔ HTTPS 無法通過 document.domain 互通 生產環境全站 HTTPS 可避免此問題
埠號必須相同 :8080 與 :80 (或 443) 不同埠視為不同源 生產環境統一標準埠,開發環境需注意
不可逆操作 一旦設定 document.domain,**無法改回** 原完整域名 設定後該頁面永久以基礎域名身分運作
iframe 載入時機 父頁面設定後,iframe 尚未載入完成前無法存取 在 iframe onload 後操作,或雙方獨立設定
Cookie 作用域影響 設定 document.domain = 'example.com' 會使 document.cookie 可讀寫 .example.com 下所有 Cookie 可能洩露敏感 Cookie,需評估安全風險
LocalStorage/SessionStorage 不共享 Storage 以完整域名 (eTLD+1) 為隔離單位,不受 document.domain 影響 跨子域共享資料需用 Cookie 或 postMessage
Port 為 null 時特殊行為 IE/舊版瀏覽器:預設埠 (80/443) 的 port 為 null,非標準埠有值 跨埠通訊不可行,統一埠號

安全性風險分析

  • 子域名劫持:若 sub.example.com 被攻擊者控制 (如廢棄子域名指向惡意伺服器),設定 document.domain = 'example.com' 後,主站頁面嵌入該子域 iframe 將面臨 XSS 風險
  • Cookie 洩露:主站設定 document.domain 後,所有子域可讀取 .example.com 作用域的 Cookie
  • 已棄用標準化:HTML Living Standard 將 document.domain 標記為 **Deprecated (已棄用)**,瀏覽器未來可能移除支援

現代替代方案 (強烈推薦)

1. postMessage (跨源通訊標準)


// 父頁面 (app.example.com)
const iframe = document.getElementById('my-iframe');
iframe.addEventListener('load', () => {
    // 發送訊息給 iframe
    iframe.contentWindow.postMessage({ type: 'INIT', data: { userId: 123 } }, 'https://api.example.com');
});

// 接收 iframe 回應
window.addEventListener('message', (e) => {
    // **必須驗證來源!**
    if (e.origin !== 'https://api.example.com') return;
    if (e.data.type === 'READY') { /* ... */ }
});

// iframe 內頁面 (api.example.com)
window.addEventListener('message', (e) => {
    if (e.origin !== 'https://app.example.com') return;
    if (e.data.type === 'INIT') {
        // 處理初始化
        e.source.postMessage({ type: 'READY' }, e.origin);
    }
});

優點:跨域、跨協議、跨埠、安全 (來源驗證)、現代標準、支援結構化資料傳遞。

2. CORS (跨源資源共享) - API 請求

若只是需要跨子域呼叫 API,後端設定 CORS 標頭即可,無需 document.domain:


// 後端回應標頭
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization

3. SharedWorker / BroadcastChannel (同源分頁通訊)

同一基礎域名下不同分頁/iframe 共享狀態:


// SharedWorker (支援度較好)
const worker = new SharedWorker('shared-worker.js');
worker.port.postMessage({ type: 'SYNC', data: ... });
worker.port.onmessage = (e) => { /* 接收廣播 */ };

// BroadcastChannel (現代、簡單)
const channel = new BroadcastChannel('app-channel');
channel.postMessage({ type: 'UPDATE', data: ... });
channel.onmessage = (e) => { /* 接收 */ };

遷移檢查清單 (從 document.domain 移至 postMessage)

  1. 識別所有跨子域 DOM/JS 互存取點
  2. 定義訊息協議 (type, payload, 錯誤碼)
  3. 雙方實作 message 事件監聽器,**嚴格驗證 e.origin**
  4. 移除所有 document.domain 設定
  5. 測試:跨域 iframe、不同協議、不同埠、多層 iframe 巢狀
  6. 驗證 Cookie/Storage 未受影響

總結

document.domain 是**歷史妥協產物**,僅限「同基礎域名、同協議、同埠」的子域間放寬同源策略。現代開發**應完全避免使用**,改用 postMessage (跨源通訊)、CORS (跨源 API)、SharedWorker/BroadcastChannel (同源分頁共享)。若維護舊系統必須使用,務必理解其不可逆性、Cookie 作用域擴大、LocalStorage 不共享、以及安全風險,並在遷移計畫中優先替換。

copyright © 萬盛學電腦網 all rights reserved