Javascript – Get top window url from frame/iframe in different domain

javascriptsame-origin-policy

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?

Best Answer

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/