简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM