从不同域中的frame/iframe获取顶部窗口url
我有一个网页,里面有一些 javascript,它将作为 iframe 嵌入到不同的网站中。我需要根据运行页面的网站来调整页面的行为。为此,我尝试从我的页面读取 top.location.href
,但这引发了错误:
不安全的 JavaScript 尝试访问 URL 为 http://website.url 的框架 来自 URL http://mypage.url 的框架。域、协议和端口 必须匹配。
有什么办法可以解决这个问题吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在最常见的情况下,您确实可以检索 iframe 的父 url。如果 iframe 仅一层深,则此方法将起作用:
varparentURL = document.referrer
https://developer.mozilla.org/en-US/docs/Web/API/document.referrer
我在创建 iframe 小部件时使用了此方法。请记住,如果您想要顶级窗口位置,但它不是 iframe 的父窗口...您将无法获得它。此外,如果您的小部件在 iframe 内导航,则引荐来源网址将会更改。
尼古拉斯·扎卡斯 (Nicholas Zakas) 的另一篇精彩文章可以在他的博客上找到:
http://www.nczonline.net/blog/2013/04/16/getting-the-url-of-an-iframes-parent/" nczonline.net/blog/2013/04/16/getting-the-url-of-an-iframes-parent/
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.