主流內核:Trident (IE)、Gecko (Firefox)、WebKit/Blink (Chrome/Safari)、Presto (Opera)。國產瀏覽器多為雙核(WebKit 高速 + Trident 相容)。
同源策略:協定、域名、埠口三者相同才算同源。防止惡意網站透過 iframe 竊取銀行頁面表單資料,或跨分頁竊取資訊。
document.domain = '主域' 即可互訪。location.hash/search 傳參,再用 parent.parent 回傳。// a.html
document.domain = 'a.com';
var _iframe = document.getElementById('_iframe');
_iframe.contentWindow.document.getElementById('_p').innerHTML = 'Content from a.html';
// b.html
document.domain = 'a.com';
<p id="_p">b.html</p>
<script src="b.com/b.js?callback=fn">,利用 script 不受同源限制,回呼函數更新頁面。
// a.html
function update_p(content){ document.getElementById('_p').innerHTML = content; }
function getFromB(){ var s=document.createElement('script'); s.src='https://b.com/b.js'; document.head.appendChild(s); }
// b.js
update_p("content from b.js");
Access-Control-Allow-Origin: https://a.com、Access-Control-Allow-Methods: GET,瀏覽器即允許跨域讀取。// a.html (父頁面)
var iframe = document.getElementById('_iframe');
iframe.contentWindow.postMessage('hello', 'https://b.com');
// b.html (iframe 頁面)
window.addEventListener('message', function(e){
if(e.origin === 'https://a.com') console.log(e.data);
}, false);
postMessage 提供安全、標準化的跨域通訊機制,支援指定目標源驗證。