Allowing a child Iframe to call a function on its parent window from a different domain

Brett picture Brett · Oct 24, 2012 · Viewed 43.3k times · Source

I have made a page which gets loaded in an IFrame and it needs to call a function on the parent page after it finishes loading.

It works locally in development (on the same domain) but in the Real World it is hosted on a completely different domain, so obviously I am running into Cross domain problems, ie:

Unsafe JavaScript attempt to access frame with URL http://[...]site1.com from frame with URL http://[...]site2.com/iframe. Domains, protocols and ports must match.

I control both the servers, so is it possible for me to put something on one or both of the servers that says they're allowed to talk to each other?

I have looked at setting "document.domain" in both the Iframe page and the parent page.

I have experimented with setting the Access Control Header:

header('Access-Control-Allow-Origin: *');

But neither of those work.

Is there any way of allowing an Iframe calling a function in the Parent window on a completely different domain when I control both servers?

Answer

dfreeman picture dfreeman · Oct 24, 2012

You can communicate between frames via the message posting API.

For example, in your child frame you might call:

parent.postMessage("child frame", "*");

And in the parent frame, register a message handler:

window.addEventListener("message", function(event) {
    console.log("Hello from " + event.data);
});