iframe
Helpers for reading and controlling iframe content โ window/document
access, postMessage, src changes, reloading, and load detection.
Import: @rtorcato/browser-common/iframe
Browser supportโ
| API | Chrome | Edge | Firefox | Safari | iOS Safari | Baseline |
|---|---|---|---|---|---|---|
HTMLIFrameElement.contentWindow | โ 1+ | โ 12+ | โ 1+ | โ 3+ | โ 1+ | Widely available |
โ
supported ยท โ partial ยท โ not supported ยท [n] see note. Generated from MDN browser-compat-data and web-features. caniuse: HTMLIFrameElement.contentWindow
Exampleโ
import {
isIframe,
postMessageToIframe,
onIframeLoad,
} from '@rtorcato/browser-common/iframe'
if (isIframe(el)) {
onIframeLoad(el, () => console.log('iframe ready'))
postMessageToIframe(el, { type: 'ping' }, 'https://example.com')
}
Exportsโ
isIframe(el)โ type guard forHTMLIFrameElementgetIframeWindow(iframe)โ returnscontentWindowornullgetIframeDocument(iframe)โ returnscontentDocumentornullpostMessageToIframe(iframe, message, targetOrigin?)โ posts a message to the iframe's window;targetOrigindefaults to the origin of the iframe'ssrcsetIframeSrc(iframe, url)โ sets the iframe'ssrcreloadIframe(iframe)โ reloads the iframe's contentisIframeLoaded(iframe)โ true oncecontentDocument.readyStateis'complete'onIframeLoad(iframe, callback)โ adds aloadevent listener
Safe usageโ
postMessageToIframe defaults targetOrigin to the origin of the iframe's src, so the browser
drops the message if the frame has navigated to another origin. When the src has an opaque origin
(data:, about:blank) there is nothing to default to, and it throws a TypeError until you pass
targetOrigin yourself.
Passing '*' sends to whatever origin the iframe is showing at that moment. Only do that on
purpose, and never with sensitive data:
postMessageToIframe(iframe, { token }) // only to the origin of iframe.src
postMessageToIframe(iframe, { type: 'ping' }, '*') // any origin: opt in explicitly
See the API reference for full signatures.