简体   繁体   English

从不同域中的frame / iframe获取顶部窗口网址

[英]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. 我有一个内部有一些javascript的网页,它将作为iframe嵌入到不同的网站中。 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: 为此,我尝试从我的页面读取top.location.href ,但这引发了一个错误:

Unsafe JavaScript attempt to access frame with URL http://website.url from frame with URL http://mypage.url . 不安全的JavaScript尝试使用URL http://mypage.url从具有URL http://website.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. 在最常见的情况下,您确实可以检索iframe的父网址。 If the iframe is just one level deep this method will work: 如果iframe只有一个级别,那么此方法将起作用:

var parentURL = document.referrer

https://developer.mozilla.org/en-US/docs/Web/API/document.referrer https://developer.mozilla.org/en-US/docs/Web/API/document.referrer

I've used this method when creating iframe widgets. 我在创建iframe小部件时使用过这种方法。 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. 请记住,如果您想要顶级窗口位置,但它不是您的iframe的父窗口...您将无法获得它。 Also, if your widget navigates within the iframe the referrer will then change. 此外,如果您的窗口小部件在iframe中导航,则引荐来源将会更改。

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/ 可以在他的博客上找到Nicholas Zakas的另一篇优秀文章: 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. 在不更改用户浏览器的情况下,无法绕过它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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