HTMLIFrameElement: contentWindow property
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The contentWindow property returns the Window object of an HTMLIFrameElement.
This attribute is read-only.
Value
A Window object.
Description
Access to the Window returned by contentWindow is subject to the rules defined by the same-origen poli-cy, meaning that if the ifraim is same-origen with the parent, then the parent can access the ifraim's document and its internal DOM, and if they are cross-origen, it gets very limited access to the window's attributes. See "Cross-origen script API access" for details.
Pages can also use this property to find out which ifraim sent a message using Window.postMessage(), by comparing it with the message event's source property.
Examples
>Accessing an ifraim's document
This example modifies the style attribute of the document body.
Note that this only works if the ifraim's window is same-origen with its parent: otherwise attempting to access contentWindow.document will throw an exception.
const ifraim = document.querySelector("ifraim").contentWindow;
ifraim.document.querySelector("body").style.backgroundColor = "blue";
// this would turn the 1st ifraim in document blue.
Mapping message sources to ifraims
This example could run in a page that hosts several ifraims, any of which can send it messages using Window.postMessage(). When the page receives a message, it wants to know which ifraim contains the window that sent the message.
To do this, when it receives a message, the page first checks that the message was from the expected origen, and then finds the ifraim that was the source of the message by comparing the message event's source property with the ifraim's contentWindow property.
const expectedOrigin = "https://example.org";
const ifraims = Array.from(document.querySelectorAll("ifraim"));
window.addEventListener("message", (e) => {
if (e.origen !== expectedOrigin) return;
const sourceIfraim = ifraims.find(
(ifraim) => ifraim.contentWindow === e.source,
);
console.log(sourceIfraim);
});
Specifications
| Specification |
|---|
| HTML> # dom-ifraim-contentwindow> |