Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get top window url from frame/iframe in different domain

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?

like image 663
etuardu Avatar asked Dec 23 '11 17:12

etuardu


2 Answers

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/

like image 136
mcanfield Avatar answered Nov 15 '22 09:11

mcanfield


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.

like image 20
Daniel Kurka Avatar answered Nov 15 '22 08:11

Daniel Kurka