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.
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.
// 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
Same-origin policy is a security feature, not a bug — use postMessage for legitimate cross-origin iframe communication.