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?
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.
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.
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.
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); });
There are a number of options here: http://softwareas.com/cross-domain-communication-with-iframes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With