同源判斷看三件事:通訊協定、主機名稱、連接埠。任一不同就算跨域:
第 3、4 兩種情況前端無解,必須靠後端代理。第 1、2 種則有多種選擇。
步驟是:在發起方的域下建一個 proxy 程式 → 前端 JS 呼叫同域的 proxy → proxy 向目標發請求並取回資料 → 把資料回傳給前端。
function GetDataFromProxy() {
var src = document.getElementById('txtSrc').value;
var request = null;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById('divData').innerHTML = request.responseText;
}
}
request.open("get", "Proxy.ashx?src=" + escape(src), false);
request.send(null);
}
proxy 端用 WebRequest 抓取目標內容再寫回 Response。實務上要留意目標頁面的編碼,範例中固定用 gb2312 讀取,換站台時必須調整。
只能解決「同父域不同子域」這一類。做法是兩邊都設定 document.domain 為父域,再由發起方建立隱藏 iframe 存取對方文件。
// 發起方
document.domain = 'a.com';
var ifr = document.createElement('iframe');
ifr.src = 'https://b.a.com/DomainTest2.htm';
ifr.style.display = 'none';
document.body.appendChild(ifr);
function GetDataFromDomain() {
var doc = ifr.contentDocument || ifr.contentWindow.document;
alert(doc.getElementById("data").value);
}
// 接收方(b.a.com)也要設定
document.domain = 'a.com';
缺點是安全性綁在一起:一個域被攻破,另一個域也會出現漏洞。
動態插入 script,src 指向對方的處理位址,對方回傳的 JavaScript 會被執行。URL 上可以帶參數,但只支援 GET。
function load_script(callback){
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = document.getElementById('txtSrc').value;
// 借鑑 jQuery 的 script 跨域做法
script.onload = script.onreadystatechange = function(){
if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
callback && callback();
script.onload = script.onreadystatechange = null; // 避免 IE 記憶體洩漏
if (head && script.parentNode) { head.removeChild(script); }
}
};
// 用 insertBefore 而非 appendChild,繞開 IE6 的 bug
head.insertBefore(script, head.firstChild);
}
伺服器端只要輸出合法 JS 即可:
Response.Clear();
Response.ContentType = "application/x-javascript";
Response.Write(String.Format(@"alert('{0}');", DateTime.Now));
Response.End();
利用 hash 改變不會觸發頁面跳轉的特性來傳值。流程是:發起方用 iframe 的 hash 把資料送給接收方 → 接收方處理後,透過一個同域代理頁把結果寫進代理頁的 hash → 代理頁再把值同步回發起方的 hash。雙方各自用 setInterval 輪詢自己的 hash。
// 發起方
function changeHash(src) {
var ifr = document.getElementById('ifr1') || document.createElement('iframe');
ifr.src = 'https://www.b.com/Test/HashTest2.htm#' + src;
ifr.style.display = 'none';
document.body.appendChild(ifr);
}
function checkHash() {
if (location.hash && location.hash.length > 1) {
changeHash(location.hash.substring(1));
}
}
setInterval(checkHash, 2000);
// 同域代理頁
function checkHash() {
if (parent && parent.parent && parent.parent.location && self.location.hash.length > 1) {
parent.parent.location.hash = self.location.hash.substring(1);
}
}
setInterval(checkHash, 500);
這種做法直接與間接層數都不少,維護成本偏高。
window.name 是跨頁面持續存在的,換 iframe 的 src 也不會被清掉,容量可達 2MB 左右。
// 接收方(b.com)
window.name = 'NameTest2';
// 發起方:先載入接收方,onload 後把 iframe 導向同域代理頁,再讀 name
var ischanged = false;
function changeSrc() {
var ifr = document.getElementById('ifr1');
if (!ischanged) {
ischanged = true;
ifr.contentWindow.location = 'https://www.a.com/Test/NameTest3.htm';
} else {
alert(ifr.contentWindow.name); // 導向同域後才能讀取
}
}
代理頁本身幾乎不用寫任何程式,重點是它必須與發起方同域。
目前最推薦的標準做法。
// 發起方
var ifr = document.getElementById('ifr');
var targetOrigin = 'https://www.b.com';
if (ifr.contentWindow.postMessage) {
ifr.contentWindow.postMessage('PostMessageTest2', targetOrigin);
}
// 接收方
window.addEventListener('message', function(event) {
if (event.origin == 'https://www.a.com') {
alert(event.data);
alert(event.source);
}
}, false);
targetOrigin 用來限制接收方的 URI(含主域名與連接埠),'*' 代表不限制。基於安全考量強烈建議明確指定,否則訊息可能被惡意網站攔走;若 targetOrigin 與對方不符,訊息會被放棄發送。接收方則務必用 event.origin 驗證來源,並用 event.data 取內容、event.source 取得對方的 window 物件。
適用於 IE6、7,原理是把 opener 物件重新指向自己定義的方法集合。做法是發起方透過 iframe.contentWindow.opener 掛上可被呼叫的方法,接收方用 window.opener.a() 呼叫,反向則由接收方設定 parent.opener。
要特別注意:這招已經被微軟的安全更新 kb2497640 封堵,打完補丁後就不能用了。
同樣是 IE6、7 的舊技巧,把方法掛在 navigator 上互相呼叫。
// 發起方
window.navigator.a = function(msg) { alert('我調用了a方法獲得了消息:' + msg); };
setInterval(function() { window.navigator.c('ccc'); }, 2000);
// 接收方
window.navigator.c = function(msg) { alert('我調用了c方法獲得了消息:' + msg); };
setInterval(function() { window.navigator.a('aaa'); }, 2000);
現代專案請優先考慮 CORS(後端設定 Access-Control-Allow-Origin)或 postMessage,兩者都是標準方案,語意清楚、安全性可控。document.domain 與 window.name 屬於歷史包袱,能用 CORS 取代就不要再用。opener 與 navigator 這兩招只存在於 IE6、7 時代,現在僅具考古價值。location.hash 輪詢則是 CORS 普及前的權宜之計。