HTMLIFrameElement: contentWindow 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

contentWindow 屬性返回 HTMLIFrameElementWindow 物件。

此屬性是隻讀的。

一個 Window 物件。

描述

contentWindow 返回的 Window 的訪問受 同源策略 定義的規則約束。這意味著,如果 iframe 與父級同源,那麼父級可以訪問 iframe 的文件及其內部 DOM;如果它們是跨域的,則對視窗的屬性只能進行非常有限的訪問。有關詳細資訊,請參閱 “跨域指令碼 API 訪問”

頁面還可以使用此屬性透過將訊息事件的 source 屬性與 iframe 的 contentWindow 屬性進行比較,來找出哪個 iframe 傳送了使用 Window.postMessage() 傳送的訊息。

示例

訪問 iframe 的文件

此示例修改文件 bodystyle 屬性。

請注意,只有當 iframe 的視窗與其父視窗同源時,此操作才有效:否則,嘗試訪問 contentWindow.document 將會丟擲異常。

js
const iframe = document.querySelector("iframe").contentWindow;

iframe.document.querySelector("body").style.backgroundColor = "blue";
// this would turn the 1st iframe in document blue.

將訊息源對映到 iframe

此示例可以在託管多個 iframe 的頁面上執行,其中任何一個 iframe 都可以使用 Window.postMessage() 向其傳送訊息。當頁面收到訊息時,它想知道是哪個 iframe 包含了傳送訊息的視窗。

為此,當收到訊息時,頁面首先會檢查訊息是否來自預期的域,然後透過將訊息事件的 source 屬性與 iframe 的 contentWindow 屬性進行比較,來查詢傳送訊息的 iframe。

js
const expectedOrigin = "https://example.org";

const iframes = Array.from(document.querySelectorAll("iframe"));

window.addEventListener("message", (e) => {
  if (e.origin !== expectedOrigin) return;

  const sourceIframe = iframes.find(
    (iframe) => iframe.contentWindow === e.source,
  );

  console.log(sourceIframe);
});

規範

規範
HTML
# dom-iframe-contentwindow

瀏覽器相容性