如何获取iframe跨域的高度
我有来自 Facebook、Twitter 等的 iframe(跨域)和 src。
我需要获取 iframe 的高度,但出现错误:
访问属性“文档”的权限被拒绝
I have iframe (cross domain) with src from Facebook, Twitter or etc.
I need to get height of iframe but I got error:
Permission denied to access property 'document'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
javascript 中没有选项可以查找跨域 iframe 高度的高度,但您可以借助一些服务器端编程来完成类似的操作。我在这个例子中使用了 PHP
There is no options in javascript to find the height of a cross domain iframe height but you can done something like this with the help of some server side programming. I used PHP for this example
情侣问题。首先,
iframe
的高度可能不是您想要的。我的意思是,它是在您控制的页面的 HTML 代码中明确设置的,并且可以通过任何 Javascript 方式轻松访问和修改。您所追求的似乎是 iframe 内页面的高度。如果是这样的话,简单的答案是你不能,至少不能使用 Facebook/Twitter 等外部服务。出于安全原因,人们可以轻松地将消息从子级传递到父级,但不能从父级传递到子级,除非在两个文档中的 javascript 中都内置了通信路径。在现代浏览器中有一个
postMessage
协议来处理这个问题。 https://developer.mozilla.org/en/DOM/window.postMessage 。但是,在这种情况下,它完全没有用,除非您正在通信的文档被设置为处理传入的 postMessage,而据我所知,Twitter/Facebook 经常不是这样。如果父文档可以与来自不同域的子文档自由通信,那么任何 javascript 都可以在您登录的任何站点上有效地执行任何系列命令。其安全影响是可怕的,幸运的是这是不可能的。
Couple issues. First, the height of the
iframe
is likely not what you want. I mean that's set explicitly in the HTML code of the page you control and is readily accessible and modifiable through any Javascript means. What it appears you are after is the height of the page inside the iframe. If that's the case, the simple answer is you can't, at least not with external services like Facebook/Twitter.Due to security reasons, one can easily pass messages from child to parent, but not from parent to child, unless a communication pathway has been built into your javascript in both documents. There is a
postMessage
protocol for handling this in modern browsers. https://developer.mozilla.org/en/DOM/window.postMessage . But, it's wholly useless in this case unless the document you are communicating with is setup to handle an incoming postMessage, which to my knowledge Twitter/Facebook frequently are not.If a parent document could freely communicate with children from different domains, then any javascript could effectively execute any series of commands on any site you're logged in as. The security implications of that are frightening and thankfully not possible.