一、同源策略
同源策略是瀏覽器的一種安全策略,它可以防止一個源載入的文檔或腳本與來自另一個源的資源進行交互。同源是指協議、主機、埠號均相同。
因此,同源限制會導致iframe無法通過JavaScript來訪問其父頁面,除非兩者處於同一個源。
二、跨域問題
跨域是指在同一頁面下,一個域名的內容訪問了另一個域名的資源,這時瀏覽器會阻止這種行為。
解決跨域的方法有多種,其中iframe跨域通信就是一種。
三、iframe實現跨域通信
1、使用postMessage
postMessage是HTML5引入的一種新特性,用於在跨域的兩個窗口之間傳遞數據。
該方法基於事件模型,傳遞的消息只有在對方窗口正確響應的情況下,才能接收到。
// 父頁面代碼 var ifr = document.getElementById('childFrame'); ifr.contentWindow.postMessage('你好子窗口', 'http://www.child.com'); window.addEventListener('message', function(e) { if (e.origin === 'http://www.child.com') { console.log(e.data); } }, false);
// 子頁面代碼 window.addEventListener('message', function(e) { if (e.origin === 'http://www.parent.com') { console.log(e.data); e.source.postMessage('你好父窗口', 'http://www.parent.com'); } }, false);
2、使用location.hash
在同一個域名下,當改變瀏覽器的地址欄時,會觸發hashchange事件。因此,可以通過修改iframe的location.hash值,來實現同源下的跨窗口通信。
// 父頁面代碼 var ifr = document.getElementById('childFrame'); txt.onkeyup = function() { ifr.src = ifr.src.split('#')[0] + '#' + txt.value; }; window.addEventListener('hashchange', function() { console.log(ifr.contentWindow.location.hash); }, false);
// 子頁面代碼 window.onhashchange = function() { console.log(location.hash); parent.window.location.hash = location.hash; };
3、使用window.name
window.name屬性在同一窗口下,即使頁面跳轉,值也不會發生變化。因此,可以通過給iframe的window.name屬性賦值,來實現同源下的跨窗口通信。
// 父頁面代碼 var ifr = document.getElementById('childFrame'); ifr.onload = function() { ifr.contentWindow.name = '你好子窗口'; }; window.onmessage = function(e) { console.log(e.data); };
// 子頁面代碼 window.name = '你好父窗口'; window.onload = function() { window.parent.postMessage(window.name, '*'); };
四、總結
通過上述三種方法,我們可以在同一個頁面的iframe之間實現跨域通信。postMessage是HTML5的推薦方法,具有較高的可靠性和安全性。而location.hash和window.name則適用於同一源的情況,但其實現起來相對較為簡單。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/159094.html