I need to access the Parent Domain URL from my Iframe which is in another domain.
For example, "example.com" is my website which has an Iframe from another parent domain, such as "google.com". Here I need to access the parent domain URL from my example.com. That is, I need to get the URL "google.com" in my "example.com" domain. Moreover, the Parent domain cannot be hard coded.
What I tried was using the following code:
window.parent.location.href()
but this results in Access denied error. How do I implement this properly in order to achieve this?
Good article here: Cross-domain communication with iframes
Also you can directly set document.domain the same in both frames (even
code has sense because resets port to null), but this trick is not general-purpose.
You have a couple of options:
Scope the domain down (see document.domain) in both the containing page and the
iframe
to the same thing. Then they will not be bound by 'same origin' constraints.Use postMessage which is supported by all HTML5 browsers for
cross-domain
communication.You can try and check for the referer, which should be the parent site if you're an iframe
you can do that like this:
You might want to take a look at these questions/answers ; they could give you some informations concerning your problem :
<iframe>
javascript access parent DOM across domains?To make things short : accessing iframe from another domain is not possible, for security reasons -- which explains the error message you are getting.
The Same origin policy page on wikipedia brings some informations about that security measure :
try
Instead of using the referrer, you can implement
window.postMessage
to communicate accross iframes/windows across domains.You post to window.parent, and then parent returns the URL.
This works, but it requires asynchronous communication.
You will have to write a synchronous wrapper around the asynchronous methods, if you need it synchronous.
Child.htm