如何使用JavaScript访问跨域iFrame内容?
我想使用此代码,
window.parent.document.getElementById('message').value += "\r\n\r\n[img]"+response+"[/img]";
它适用于来自同一域的页面,但不适用于 iFrame 中加载的另一个域的网站。我该怎么做呢?
I would like to use this code
window.parent.document.getElementById('message').value += "\r\n\r\n[img]"+response+"[/img]";
It works fine for pages coming from the same domain, but not for sites from another domain loaded in the iFrame. How can I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以实现 window.postMessage 来跨域的 iframe/windows 进行通信。
儿童.htm
You can implement window.postMessage to communicate accross iframes/windows across domains.
Child.htm
如果您的浏览器禁用了安全性,则可以,对于 chrome,它是
更新:我很惊讶人们一直致力于它,因为他们认为它有害,所以在这里我为那些不了解网络安全基础知识但仍在尝试的人们添加一些额外的详细信息为之发展。
请勿使用此解决方案
您正在使用不受您信任的 Chrome 插件或应用,或者
您已打开, Chrome 中的其他网站,或者
您有一些恶意 chrome 进程
您的网站正在使用任何外部资源.
为了使该解决方案完全安全,请将防火墙配置为阻止除要建立 CORS 连接的连接之外的所有连接。
另外,如果您的连接端点不受信任,请勿使用此解决方案。
You can if your browser have disabled security, for chrome it's
Update: I'm surprised that people keep devoting it because they consider it harmful, so here I add some additional details for peoples who don't know basics of web security and still try to develop for it.
DON'T use this solution if
you are using chrome plugins or apps which are not trusted by you, or
you have opened other sites in the chrome, or
you have some malicious chrome processes
your site is using any external resources.
To make this solution completely safe, configure your firewall to block all connections except one to which you are making CORS connection.
Also, don't use this solution if your connection endpoint isn't trusted.
看看 easyXDM,它是一个易于使用的库,为用于启用跨域消息传递的多种技巧提供了统一的 API,从 postMessage 到作为最后手段的 FIM 技巧。
Twitter 和 Disqus 等主要服务都使用这种方式。
Take a look at easyXDM, it's an easy to use library that provides a unified API for several tricks used to enable cross domain messaging, ranging from postMessage to the FIM-trick as a last resort.
This is what is used by major services such as Twitter and Disqus.
由于同源政策限制,这是不允许的。
Due to same origin policy restrictions this is not allowed.
如前所述,这属于同源策略,但有一些技巧允许与 iframe 进行有限的通信。看看 http://ajaxify.com/run/crossframe/
As stated, this falls under same origin policy, but there are some tricks that allow limited communication with the iframe. Take a look at http://ajaxify.com/run/crossframe/
你不能。这称为同源策略,可防止 javascript 跨域访问内容。
You can't. This is called the same origin policy, and prevents javascript accessing content across domains.