假設 a.com 上的 get.html 想讀取 b.com 上的 data.html 內容——兩者不在同一個來源,這就是跨域。
瀏覽器之所以要攔,源自同源政策(Same-Origin Policy):為了保護網站安全,避免外部網站的腳本擅自修改本站內容或偷讀資料。判斷是否同源的依據有三項——通訊協定、網域、連接埠,三者必須完全相同。

下表列出常見的組合是否算同源:
但現實中我們確實常常需要跨來源取資料。以下六種是常見解法。
談跨域不能不談 JSONP。它是「JSON with Padding」的縮寫,可以理解為「填上了內容的 JSON」。
原理是借用 <script> 標籤不受同源政策限制的歷史漏洞:頁面上宣告一個 callback 函式,然後引入 b.com 的 js 檔,而該檔案的內容是 callback({msg:"tqtan"});。腳本一載入就呼叫了本地的 callback,資料於焉傳遞完成。
最簡單粗暴的寫法:
$.getJSON("https://b.com/dataServlet?callback=?", function (data) {
console.log(data.msg);
});
這裡的 callback=? 是個佔位符,jQuery 會自動填入一段唯一字串,例如 jQuery17207481773362960666_1332575486681。伺服器只需把這個 callback 名稱包在回應裡即可:
// dataServlet.java
String callback = req.getParameter("callback");
PrintWriter out = resp.getWriter();
out.print(callback + "('msg','tqtan')");
$.ajax({
url: 'https://b.com/dataServlet?words=hi',
dataType: 'jsonp',
jsonp: 'jsoncallback',
jsoncallback: 'tqtan',
success: function (data) {
console.log(data.msg);
},
error: function (e) {
console.log(e);
}
});
可以自訂 callback 的名稱(這裡是 tqtan),也能帶參數。要注意的是:JSONP 只能是 GET 請求,因為它本質上就是引入一個 script 檔。
JSONP 的缺點也很明確:只支援 GET,且把一段可執行程式碼當資料載入,等於完全信任對方。若來源不可信,這是一個安全風險。
若 get.a.com 要讀 data.a.com 的內容,兩邊只要都把 document.domain 設為共同的父網域 a.com,就能互相操作。
// get.html
var iframe = document.createElement("iframe");
iframe.src = "https://data.a.com/data.html";
iframe.style.display = "none";
document.body.appendChild(iframe);
document.domain = 'a.com';
iframe.onload = function () {
var otherDocument = iframe.contentDocument ||
iframe.contentWindow.document;
// otherDocument 就是另一個頁面的 document,接下來愛做什麼都行
};
// data.html
document.domain = 'a.com';
hash 就是網址 # 後面的部分,例如 https://example.com/index.html#data 裡的 #data。它變動時不會重新載入頁面,因此常被拿來做跨域溝通。
流程是這樣:get.html 建立一個 iframe 指向 data.html 並用 hash 傳參;data.html 讀取自己的 hash 後,再建立另一個 iframe 指向 a.com 上的 proxy.html,把回應寫進 hash;proxy.html 與 get.html 同源,於是能修改父視窗的 hash;get.html 則用 setInterval 定時監聽 hash 變化來接收資料。
// a.com/get.html
var iframe = document.createElement('iframe');
iframe.src = 'https://b.com/data.html#data';
iframe.style.display = 'none';
document.body.appendChild(iframe);
// 週期檢測 hash 更新
function getHash() {
var data = location.hash ? location.hash.substring(1) : '';
console.log(data);
}
setInterval(getHash, 1000);
// a.com/proxy.html —— 負責把 b.com 的訊息轉交給同源的父頁
parent.location.hash = self.location.hash.substring(1);
// b.com/data.html
if (location.hash) {
var data = location.hash;
doSth(data);
}
function doSth(data) {
console.log("from a.com: " + data);
var msg = "hello i am b.com";
var iframe = document.createElement('iframe');
iframe.src = "https://a.com/proxy.html#" + msg;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
為什麼需要 proxy.html?因為 get.html 與 data.html 不同源,data.html 無權修改 get.html 的 hash。proxy.html 與 get.html 同源,因此可以透過 parent.location.hash 把訊息遞上去。這就是「代理頁面」存在的意義。
這個技巧相當巧妙:window.name 的值在不同頁面(甚至不同網域)之間載入後依然存在,而且容量可達數 MB,遠超其他傳遞方式。
// a.com/get.html
var state = 0;
var iframe = document.createElement('iframe');
iframe.src = 'https://b.com/data.html';
iframe.style.display = 'none';
var loadfn = function () {
if (state === 1) {
// 此時 iframe 已跳回同源頁面,可以安全讀取 name
var data = iframe.contentWindow.name;
console.log(data);
} else if (state === 0) {
state = 1;
// 第一次 onload:把 iframe 導向同源代理頁
iframe.contentWindow.location = "https://a.com/proxy.html";
}
};
if (iframe.attachEvent) {
iframe.attachEvent('onload', loadfn);
} else {
iframe.onload = loadfn;
}
document.body.appendChild(iframe);
// a.com/proxy.html —— 清理痕跡,避免 iframe 殘留
iframe.contentWindow.document.write('');
iframe.contentWindow.close();
document.body.removeChild(iframe);
// b.com/data.html
var data = "hello,tqtan";
window.name = data;
關鍵在於「第一次 onload 後立刻把 iframe 導向同源頁面」,一旦同源,讀 contentWindow.name 就完全合法了。用 state 旗標區分第一次與第二次 onload,是這個技巧的核心。
HTML5 提供的 postMessage() 是公認最優雅的方案,用法直觀:發送方呼叫 postMessage(),接收方監聽 message 事件。
// a.com/send.html
var iframe = document.createElement("iframe");
iframe.src = "https://b.com/receive.html";
document.body.appendChild(iframe);
iframe.contentWindow.postMessage("hello", "https://b.com");
// b.com/receive.html
window.addEventListener('message', function (event) {
// 務必檢查來源!
if (event.origin == 'https://a.com') {
console.log(event.data);
console.log(event.source); // 發送源的 window 參照
}
}, false);
postMessage() 的第二個參數是「目標來源」,不應省略;接收端也一定要檢查 event.origin。少了這兩道防線,等於對所有網站敞開大門。
前面五種都是前端硬做的變通,而 CORS 是瀏覽器與伺服器合作的正式標準,也是最推薦的方案。
CORS 是 Cross-Origin Resource Sharing 的縮寫。相比 JSONP 只能 GET,CORS 支援所有類型的 HTTP 請求,並能攜帶 cookie 與自訂標頭。代價是需要後端設定回應標頭,且舊版 IE 不支援。
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// 標準支援 CORS
// withCredentials 只存在於 XMLHttpRequest Level 2
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// 退路:IE8/IE9 用 XDomainRequest
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// 瀏覽器不支援 CORS
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
伺服器端只要設定回應標頭即可。以 Java 為例:
response.setHeader("Access-Control-Allow-Origin", "*");
基於安全考量,正式環境請把 * 換成明確的網域,例如 https://a.com,而不是讓所有網站都能讀你的資料。
新專案請直接走 CORS,這是標準、支援完整、語意清楚。若無法改動後端,且資料量不大、可接受 GET only,JSONP 仍能用;同主網域的子網域溝通,postMessage 是最簡潔的選擇。至於 hash 與 window.name 這兩個技巧,理解原理有助於讀懂老系統,但新專案沒有理由再用。
另外,開發階段若只是本機 API 連不上,可以考慮用 dev server 的 proxy 設定繞過,這比在程式碼裡塞變通做法乾淨得多。