iframe 做爲html頁面構成的基本元素之一,具有下面的特色html
關於html元素的構成的內容劃分,這張圖有一個很好的解釋:算法
iframe具有一些節點屬性,以下:瀏覽器
src:資源的地址安全
爲何要這麼作? 在iframe中,你能夠加載不一樣的內容,這類內容不會被瀏覽器再一次進行解釋,舉個例子來講: 若是你想嵌入一些特別的符號,你就能夠和sandbox聯合使用(例子中的amp就是一個特殊符號) <iframe sandbox srcdoc="<p>hey that's earl's table. <p>you should get earl&amp;me on the next cover." > </iframe>
allow-forms, allow-modals, allow-orientation-lock, allow-pointer-lock, allow-popups, allow-popups-to-escape-sandbox, allow-presentation, allow-same-origin, allow-scripts, allow-top-navigation, and allow-top-navigation-by-user-activation.
好比你嵌入了一篇文章,這篇文章有全屏觀看的操做 <iframe src="http://article...." > </iframe> // http://article.... <div id='article' onclick={handleFullClick} > // 省略文章內容 </div> script: const handleFullClick = () => { const article = document.getElementById('article'); article.requestFullscreen(); }
// 嵌入的iframe是否容許定位 <iframe src="https://maps.example.com/" allow="geolocation"></iframe>
enum ReferrerPolicy { "", "no-referrer", "no-referrer-when-downgrade", "same-origin", "origin", "strict-origin", "origin-when-cross-origin", "strict-origin-when-cross-origin", "unsafe-url" };
ok,總結起來就是,iframe能夠嵌入第三方資源,而且能夠對第三方資源進行策略限制,爲了安全,畢竟第三方,須要必定的兜底處理。ide
iframe是被瀏覽器的當前頁面以第三方資源的形式嵌入的,若是想兩者之間實現通訊,就須要經過postMessage佈局
otherWindow.postMessage(message, targetOrigin, [transfer]);
Example:post
父窗口: // 假定iframe的id = iframe document.getElementById('iframe').contentWindow.postMessage('123', '*'); 子窗口: Window.addEventListener('message', ({ data }) => { console.log('data'); // 向父窗口發送消息 if(window.parrent !== window.self) { window.parrent.postMessage('456', '*'); } })