I have a web page with some javascript inside that will be embedded as iframe in different websites. I need to adjust the behaviour of my page according to the website in which it's being run. For this purpose, I tried to read top.location.href
from my page, but that raised an error:
Unsafe JavaScript attempt to access frame with URL http://website.url from frame with URL http://mypage.url. Domains, protocols and ports must match.
Is there some way to go around this?
In the most common case you can indeed retrieve the parent url of the iframe. If the iframe is just one level deep this method will work:
var parentURL = document.referrer
https://developer.mozilla.org/en-US/docs/Web/API/document.referrer
I've used this method when creating iframe widgets. Just remember that if you want the top level window location, but it is not the parent window of your iframe...you won't be able to get it. Also, if your widget navigates within the iframe the referrer will then change.
Yet another excellent write-up by Nicholas Zakas can be found on his blog here: http://www.nczonline.net/blog/2013/04/16/getting-the-url-of-an-iframes-parent/
This is as you stated the same origin policy and it is in place for security reasons. Without changing the users browser there is no way around it.
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