Javascript 获取跨域 iFrame 内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6474484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Cross-Domain iFrame content
提问by kay-zar
I would like to know how I can get content from an IFrame cross-domain?
我想知道如何从 IFrame 跨域获取内容?
I have no problem getting content from a non-cross-domain iFrame, but when it's located on another domain, JavaScript doesn't allow access.
我从非跨域 iFrame 获取内容没有问题,但是当它位于另一个域时,JavaScript 不允许访问。
回答by robertc
You use Cross Document Messaging, here's an example. Here's the significant code from the parent page:
window.addEventListener('message', receiver, false);
function receiver(e) {
document.getElementById('message').value = e.data;
}
function update_child() {
var el = document.getElementsByTagName('iframe')[0];
el.contentWindow.postMessage('Updated from parent', '*');
}
The child page has identical code - note that you need to be able to implement the interface on both domains for this to work, either by yourself, if you control both, or in co-operation with the owner of the other domain. In production code you should set (and check) the origin.
子页面具有相同的代码 - 请注意,您需要能够在两个域上实现接口才能使其工作,无论是您自己(如果您控制这两个域),还是与另一个域的所有者合作。在生产代码中,您应该设置(并检查) origin。
回答by Quentin
Short of requesting it via a proxy on your own server, you can't.
如果没有通过您自己服务器上的代理请求它,您就不能。
The same origin policyprevents it (and for good reason; I would be very unhappy if you loaded my banking site in your iframe and read all my account details)
该同源策略阻止它(并有很好的理由;如果你在你的iframe中加载我的银行网站,我会很不高兴,阅读所有我的帐户详细资料)