Skip to main content

iframe

Helpers for reading and controlling iframe content โ€” window/document access, postMessage, src changes, reloading, and load detection.

Import: @rtorcato/browser-common/iframe

๐Ÿ“– MDN: HTMLIFrameElement

Browser supportโ€‹

APIChromeEdgeFirefoxSafariiOS SafariBaseline
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 for HTMLIFrameElement
  • getIframeWindow(iframe) โ€” returns contentWindow or null
  • getIframeDocument(iframe) โ€” returns contentDocument or null
  • postMessageToIframe(iframe, message, targetOrigin?) โ€” posts a message to the iframe's window; targetOrigin defaults to the origin of the iframe's src
  • setIframeSrc(iframe, url) โ€” sets the iframe's src
  • reloadIframe(iframe) โ€” reloads the iframe's content
  • isIframeLoaded(iframe) โ€” true once contentDocument.readyState is 'complete'
  • onIframeLoad(iframe, callback) โ€” adds a load event 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.