jQuery 加载后如何获取 iframe 主体?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4149890/
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
How get iframe body after load?
提问by user207123
I need obtain the iframe body after iframe load
我需要在 iframe 加载后获取 iframe 主体
回答by PleaseStand
document.getElementById('frame').contentDocument.body
will give you it in pure JavaScript, assuming that the iframe's ID is frame
. In jQuery, that would be $('#frame').contents().find('body')
.
document.getElementById('frame').contentDocument.body
假设 iframe 的 ID 是frame
. 在 jQuery 中,这将是$('#frame').contents().find('body')
.
Note that because of the same-origin policy, this will only work if the iframe and the surrounding pages' URLs have exactly the same hostname and port number.
请注意,由于同源策略,这仅在 iframe 和周围页面的 URL 具有完全相同的主机名和端口号时才有效。
Edit:You commented that you get an "Access denied" error when you tried this code. The same-origin policy is why this happens. The excellent Browser Security Handbook has information about this. A close reading of that web page will suggest that there are ways to break through, though this is not possible unless you control the enclosed site because of security and privacy reasons.
编辑:您评论说您在尝试此代码时收到“拒绝访问”错误。同源策略是发生这种情况的原因。优秀的浏览器安全手册有这方面的信息。仔细阅读该网页会发现有一些方法可以突破,尽管出于安全和隐私原因,除非您控制封闭的站点,否则这是不可能的。
回答by Maksim Vi.
Because of security reasonsthere is no way to get iframe content with javascript if it is on different domain. Take a look at JSONPinstead.
由于安全原因,如果 iframe 内容位于不同的域中,则无法使用 javascript 获取 iframe 内容。来看看JSONP。