Get top window url from frame/iframe in different domain

最后都变了- 提交于 2020-08-24 08:12:27

问题


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?


回答1:


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.




回答2:


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/



来源:https://stackoverflow.com/questions/8618974/get-top-window-url-from-frame-iframe-in-different-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!