Iframe contentWindow on different domain

1.6k views Asked by At

I'm working on custom scrolling for a page that will be hosted on domain B and opened in an iframe from a site hosted on domain A. I need to get frame's height and width like this:

clientHeight = parent.document.getElementById("mainForm").contentWindow.innerHeight || parent.document.getElementById("mainForm").offsetHeight;

This works when both pages are on the same domain but doesn't work when they're on different domains. I know I can use postMessage to request and get this information, I'm just not sure how to access frame size from the hosting page on domain A either. Things like window.frames['abc'].contentWindow are also blocked. Any ideas?

P.S.: I did search this topic and found many similar topics, none of them answers this specific questions.

1

There are 1 answers

0
Hamish Rouse On

The “Same Origin” (same site) policy limits access of windows and frames to each other.

The idea is that if a user has two pages open: one from john-smith.com, and another one is gmail.com, then they wouldn’t want a script from john-smith.com to read our mail from gmail.com. So, the purpose of the “Same Origin” policy is to protect users from information theft.

https://javascript.info/cross-window-communication

From the same article - a possible solution is to use the PostMessage API to communicate between the two pages:

https://javascript.info/cross-window-communication#postmessage

More info at: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage