使用纯 JavaScript 获取 iframe 的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16755347/
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
Getting Contents of Iframe with Pure JavaScript
提问by EasyBB
I already can get the content of an Iframe with jQuery, though I would like to learn how to get it with pure JavaScript.
我已经可以使用 jQuery 获取 Iframe 的内容,但我想学习如何使用纯 JavaScript 获取它。
This is what I have so far.
这就是我迄今为止所拥有的。
var frame = document.getElementById('awc_frame');
var easyBB = frame.contentWindow.document.body.innerHTML;
easyBB.getElementById('chatbox-title').innerText="Chatbox";
What am I doing wrong, please help. Also originally the frame does not have an ID, and I already tried this
我做错了什么,请帮忙。另外原来框架没有ID,我已经试过了
var frame = document.frames['awc_frame'];
Is that cross browser efficient? And then how do I get the contentWindow? Just some explanation so I can do this with JavaScript and not jQuery. jQuery version is this
那跨浏览器效率高吗?然后我如何获得 contentWindow?只是一些解释,所以我可以用 JavaScript 而不是 jQuery 来做到这一点。jQuery 版本是这个
var frame = $('#avacweb_chat iframe');
var easyBB = $('#chatbox-title',frame.contents()).text('Chatbox');
回答by Nile
If it is on the same domain, try this. It won't let you access iframe contents if the iframe is of a different origin than the window that you are viewing.
如果它在同一个域中,请尝试此操作。如果 iframe 的来源与您正在查看的窗口不同,则它不会让您访问 iframe 内容。
var iframe = document.getElementById("awc_frame");
var iframe_contents = iframe.contentDocument.body.innerHTML;
Working example with jsfiddle iframe viewing a page on the same domain:
使用 jsfiddle iframe 查看同一域上的页面的工作示例: