Html-iframe

基本概念

iframe 做爲html頁面構成的基本元素之一,具有下面的特色html

  • 行內元素,默認寬度300px,高度150px
  • 遵循流式佈局(Flow content),位於body元素內
  • 段落內容(Phrasing content),能夠構成一個段落
  • 嵌入資源(Embedded content),相似的還有video、img等
  • 可交互(Interactive content),相似的還有button、textarea等
  • 無子節點(Palpable content),iframe標籤內部不嵌入任何元素,相反,div標籤內就能夠嵌入其餘元素 關於html元素的構成的內容劃分,這張圖有一個很好的解釋:

基本用法

iframe具有一些節點屬性,以下:算法

  • src:資源的地址
    • 絕對地址: 會加載對應地址的資源
    • 相對地址: 會加載當前頁面,默認同源
    • about:blank: 會顯示一個空白頁
  • srcdoc: iframe中須要render的內容,會覆蓋掉對應的資源的內容
爲何要這麼作?
在iframe中,你能夠加載不一樣的內容,這類內容不會被瀏覽器再一次進行解釋,舉個例子來講:
若是你想嵌入一些特別的符號,你就能夠和sandbox聯合使用(例子中的amp就是一個特殊符號)

<iframe
  sandbox
  srcdoc="<p>hey that's earl's table. <p>you should get earl&amp;amp;me on the next cover."
  >
</iframe>
複製代碼
  • name:給嵌入的文檔資源起的一個名字
  • sandbox:設置一些安全規則,規定了嵌入資源的一些行爲,是否容許彈窗的行爲
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.
複製代碼
  • allowfullScreen: 規定嵌入資源是否容許全屏,true爲容許
好比你嵌入了一篇文章,這篇文章有全屏觀看的操做
<iframe
  src="http://article...."
>
</iframe>

// http://article....

<div
  id='article'
  onclick={handleFullClick}
>
// 省略文章內容
</div>

script:
const handleFullClick = () => {
  const article = document.getElementById('article');
  article.requestFullscreen();
}
複製代碼
  • allow,設置是否容許對應的特徵策略
// 嵌入的iframe是否容許定位
<iframe src="https://maps.example.com/" allow="geolocation"></iframe>
複製代碼
  • referrerpolicy:是以枚舉類型,設置了一些策略
enum ReferrerPolicy {
  "",
  "no-referrer",
  "no-referrer-when-downgrade",
  "same-origin",
  "origin",
  "strict-origin",
  "origin-when-cross-origin",
  "strict-origin-when-cross-origin",
  "unsafe-url"
};
複製代碼
  • contentDocument和contentWindow:返回的是iframe對應的document和window與當前頁面的document和window對應。 ok,總結起來就是,iframe能夠嵌入第三方資源,而且能夠對第三方資源進行策略限制,爲了安全,畢竟第三方,須要必定的兜底處理。

經常使用的業務場景

與iframe之間的通訊

iframe是被瀏覽器的當前頁面以第三方資源的形式嵌入的,若是想兩者之間實現通訊,就須要經過postMessage瀏覽器

otherWindow.postMessage(message, targetOrigin, [transfer]);
複製代碼
  • otherWindow: 窗口的引用,也就是你要向誰發送消息
  • message:發送消息的內容,會被結構化克隆算法序列化
  • targetOrigin:指定哪些窗口能夠沒收到消息
  • transfer:transfer中的對象,發送以後,就會被垃圾回收,不存儲任何內容

Example:安全

父窗口:
// 假定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', '*'); 
    }
})

複製代碼

參考資料

相關文章
相關標籤/搜索