Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk3 min

Iframe Accessing Variables: Same-Origin Access and Cross-Origin Messaging

An iframe has its own JavaScript window. Same-origin pages can access deliberately exposed values through contentWindow; cross-origin pages should use validated postMessage() messages.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An iframe has its own JavaScript window. If the parent page and iframe are same-origin, the parent can access values the iframe exposes through iframe.contentWindow. If they are cross-origin, direct access is restricted; use postMessage() with origin checks and a defined message format instead.

First, check whether the pages are same-origin

Two pages are same-origin only when their scheme, host, and port match. For example, a difference between HTTP and HTTPS, between hostnames, or between ports makes them cross-origin. The browser’s same-origin policy governs whether one document can directly inspect or change another.

An iframe’s contentWindow gives the parent a reference to the iframe’s Window, but it does not override those restrictions. The contentWindow property is a reference, not permission for unrestricted access.

Page relationship Direct access to iframe variables Approach Important check
Same-origin Possible for values or functions the child page exposes Use the iframe element’s contentWindow Wait for the child page to load; access remains coupled to its implementation
Cross-origin Blocked by the same-origin policy Exchange data with postMessage() Check sender origin and validate message data

Access values in a same-origin iframe

After the iframe has loaded, the parent can use contentWindow to call a function or read a value that the child deliberately exposes on its Window. For example, the child could define window.getStatus, and the parent could call it through the iframe’s contentWindow. Exposing a function or a small, intentional interface is generally clearer than depending on incidental internal variables.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Direct access depends on both documents remaining same-origin and on the child continuing to expose the value or function in the expected way. If either page moves to a different origin, this approach no longer works; use messaging instead.

Exchange data with a cross-origin iframe

For cross-origin pages, define a small message contract: agree on the message’s type and fields, send it with postMessage(), and validate it when received. MDN describes postMessage() as a way to enable communication between Window objects, including a page and an embedded iframe.

Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

When the sender knows the receiver’s origin, it should specify that exact origin—including scheme, host, and port—as targetOrigin, rather than using a wildcard. The receiver should check event.origin, optionally confirm event.source when it matters which window sent the message, and validate the message’s type and fields before acting on it.

// Parent page: send a message to the iframe at its known origin.
const frame = document.querySelector("iframe");
const iframeOrigin = "https://child.example";
frame.contentWindow.postMessage(
  { type: "status-request" },
  iframeOrigin
);

// Child page: accept only the expected sender and message shape.
const parentOrigin = "https://parent.example";
window.addEventListener("message", (event) => {
  if (event.origin !== parentOrigin) return;
  if (event.source !== window.parent) return;

  const message = event.data;
  if (!message || message.type !== "status-request") return;

  // Handle the validated request.
});

Replace the example origins with the actual origins of the pages. The child can reply to the parent with window.parent.postMessage(data, parentOrigin), using the parent’s known origin as the target. A message’s arrival alone does not make it trustworthy: verify who sent it and whether its contents match the agreed format before using it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why a particular SitePoint code sample may need a different fix

The specific SitePoint thread’s code and accepted answer could not be verified, so there is no basis to claim that a particular snippet or error was reproduced. The key diagnostic is the origin relationship: same-origin pages can use an exposed value or function through contentWindow; cross-origin pages need a validated postMessage() exchange.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.