SyntaxStudy
Sign Up
HTML Same-Origin Policy and iframes
HTML Intermediate 5 min read

Same-Origin Policy and iframes

Same-Origin Policy

JavaScript cannot access the DOM or properties of an iframe from a different origin due to the same-origin policy. Two URLs share an origin only if they have the same protocol, host, and port.

Example
// Same-origin iframe — this works
const iframe = document.querySelector("iframe");
const iframeDoc = iframe.contentDocument; // OK if same origin

// Cross-origin iframe — this throws a SecurityError
try {
  const crossDoc = iframe.contentDocument; // Error!
} catch (e) {
  console.log("Cross-origin access blocked:", e.message);
}

// Use postMessage for cross-origin communication instead
Pro Tip

Same-origin policy is a security feature, not a bug — use postMessage for legitimate cross-origin iframe communication.