值
一个 Window 对象。
描述
对 contentWindow 返回的 Window 的访问受 同源策略 定义的规则约束。这意味着,如果 iframe 与父级同源,那么父级可以访问 iframe 的文档及其内部 DOM;如果它们是跨域的,则对窗口的属性只能进行非常有限的访问。有关详细信息,请参阅 “跨域脚本 API 访问”。
页面还可以使用此属性通过将消息事件的 source 属性与 iframe 的 contentWindow 属性进行比较,来找出哪个 iframe 发送了使用 Window.postMessage() 发送的消息。
示例
访问 iframe 的文档
此示例修改文档 body 的 style 属性。
请注意,只有当 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 |
浏览器兼容性
加载中…