Iframe詳解html
<iframe src="demo.html" height="300" width="500" name="demo" scrolling="auto" sandbox="allow-same-origin"></iframe>
iframe的一些基本屬性:前端
咱們能夠經過contentWindow
和contentDocument
兩個API獲取iframe的window對象和document對象。html5
let iframe = document.getElementById('demo'); let iwindow = iframe.contentWindow; // 獲取iframe的window對象 let idoc = iframe.contentDocument; // 獲取iframe的document對象
剛剛咱們提到了iframe的name屬性,咱們也能夠經過window.frames[iframeName]來調用iframe ajax
let iframe = window.frames['demo']
window.self
,
window.parent
,
window.top
這三個屬性分別獲取自身window對象,父級window對象,頂級window對象。
iframe1.self === iframe1 iframe1.parent === iframe2 iframe2.parent === window iframe1.top === window
什麼是同域什麼跨域咧?同域跨域的區別在哪咧?咱們通常會使用iframe來進行父子頁面的通訊,然鵝父子頁面是否同域決定了它們之間可否進行通訊。後端
js遵循同源策略,即同協議,同域名,同端口號,不然都算跨域。跨域
對於主域相同子域不一樣的兩個頁面,咱們能夠經過document.domain + iframe來解決跨域通訊問題。瀏覽器
document.domain = 'easonwong.com'
(這樣瀏覽器就會認爲它們處於同一個域下),而後網頁a再建立iframe上網頁b,就能夠進行通訊啦~
document.domain = 'easonwong.com'; var ifr = document.createElement('iframe'); ifr.src = 'http://script.easonwong.com'; ifr.style.display = 'none'; document.body.appendChild(ifr); ifr.onload = function(){ let doc = ifr.contentDocument || ifr.contentWindow.document; // 在這裏操縱b.html };
網頁b安全
document.domain = 'easonwong.com';
postMessage是html5的新特性app
postMessage介紹框架
兼容性 IE8以上
咱們能夠經過html5這個新特性進行iframe間的跨域通訊,使用postMessage進行數據傳遞,經過Message監聽通訊事件。
網頁a
document.domain = 'easonwong.com'; var ifr = document.createElement('iframe'); ifr.src = 'http://script.easonwong.com'; ifr.style.display = 'none'; document.body.appendChild(ifr); // 發送數據 ifr.postmessage('hello, I`m a', 'http://script.easonwong.com');
網頁b
// 監聽message事件 window.addEventListener('message', receiver, false); function receiver(e) { if (e.origin == 'http://www.easonwong.com') { if (e.data == 'hello, I`m a') { e.source.postMessage('hello, I`m b', e.origin);信息 } } }
在移動端Hybrid混合模式中常常用到JSBridge進行JS和Native之間的通訊,其中咱們能夠經過iframe的方式實現JS調用Native的方法。
以上提到的方法就是URL SCHEME攔截
在好久好久好久之前,久到ajax還沒出現的時候,人們會用iframe來進行異步請求。大概就是異步建立iframe,而後後臺返回數據在iframe中,咱們在從裏面獲取數據。
例如在我作過的一個項目中,經過iframe.src傳入一個文件下載地址,實現無需打開新窗口下載文件。
引用/展現第三方內容
須要獨立樣式和帶有交互的內容,例如幻燈片
sandbox沙箱隔離
歷史記錄管理
在前端領域,咱們能夠經過window.top
來防止咱們頁面被嵌套。
if(window != window.top){ window.top.location.href = myURL; }
或者經過window.location.host
來檢測是否跨域了
if (top.location.host != window.location.host) { top.location.href = window.location.href; }
然後端也能夠作對應的防範措施,經過設置X-Frame-Options響應頭來確保本身網站的內容沒有被嵌到別人的網站中去,也從而避免了點擊劫持 (clickjacking) 的攻擊。
內容安全策略(CSP)用於檢測和減輕用於 Web 站點的特定類型的攻擊,例如 XSS 和數據注入等。
經過CSP配置sandbox和child-src能夠設置iframe的有效地址,它限制適iframe的行爲,包括阻止彈出窗口,防止插件和腳本的執行,並且能夠執行一個同源策略。
咱們能夠在html頭部中加上<meta>
標籤
<meta http-equiv="Content-Security-Policy" content="child-src 'unsafe-inline' 'unsafe-eval' www.easonwong.com">
或者經過HTTP頭部信息加上Content-Security-Policy字段