Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 721
Brett Avatar asked Oct 24 '12 03:10

Brett


People also ask

Can I load an iframe from a different domain?

Generally, web application allows script running between pages(parent and iframe pages) in the same domain based on same-origin-policy. Unfortunately it does not support scripts if different domain. The policy does not allow it.

How can an iframe communicate with its parent?

All you have to do is first dispatch an event from the iframe to the parent that notifies the parent that the iframe is loaded (essentially a "ready message"). The parent will be listening for messages and if it receives the "ready message" event, it can then reply to the iframe with whatever message you want to send.

Can iframe access parents?

When a page is running inside of an iframe, the parent object is different than the window object. You can still access parent from within an iframe even though you can't access anything useful on it. This code will never cause an error even when crossing origins.


2 Answers

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); }); 
like image 101
dfreeman Avatar answered Oct 06 '22 04:10

dfreeman


There are a number of options here: http://softwareas.com/cross-domain-communication-with-iframes

like image 26
iivel Avatar answered Oct 06 '22 03:10

iivel