iframe的innerHTML是空白的,因为您的iframe标记不会围绕父文档中的任何内容。为了从iframe的src属性所引用的页面中获取内容,您需要访问iframe的contentDocument属性。但是,如果src来自其他域,则会引发异常。这是一项安全功能,可防止您在其他人的页面上执行任意JavaScript,这会产生跨站点脚本漏洞。这是一些示例代码,说明了我在说什么:
<script src="http://prototypejs.org/assets/2009/8/31/prototype.js" type="text/javascript"></script>
<h1>Parent</h1>
<script type="text/javascript">
function on_load(iframe) {
try {
// Displays the first 50 chars in the innerHTML of the
// body of the page that the iframe is showing.
// EDIT 2012-04-17: for wider support, fallback to contentWindow.document
var doc = iframe.contentDocument || iframe.contentWindow.document;
alert(doc.body.innerHTML.substring(0, 50));
} catch (e) {
// This can happen if the src of the iframe is
// on another domain
alert('exception: ' + e);
}
}
</script>
<iframe id="child" src="iframe_content.html" onload="on_load(this)"></iframe>
为了进一步说明该示例,请尝试将其用作iframe的内容:
<h1>Child</h1>
<a href="http://www.google.com/">Google</a>
<p>Use the preceeding link to change the src of the iframe
to see what happens when the src domain is different from
that of the parent page</p>