如何在Javascript中的iframe元素中获取元素?

Tho*_*son 6 javascript iframe google-chrome

我有如下一个元素的文档里面,我能得到通过iframe元素document.getElementById('iframe_id'),但如何得到这个iframe中的元素?我试过了iframeElement.contentWindow,返回的DOMWindow没有属性.也试过iframeElement.docuemntiframeElement.contentDocument,两者是不确定的.我怎么才能得到它?我在实验中使用了最新的Chrome.

这是iframe元素

<iframe id='iframe_id'>
<html>
<body>many content here</body>
</html>
</iframe>
Run Code Online (Sandbox Code Playgroud)

mpl*_*jan 5

如果内容与询问它的脚本具有相同的协议,域和端口号,则只能查询iframe中的内容.它被称为SAME ORIGIN

如果是这种情况,那么此代码将显示内容.如果不是 - 您无法从普通html页面中的普通脚本访问iframe

演示 - 在IE8,Chrome 13和Fx6中测试过

function showIframeContent(id) {
  var iframe = document.getElementById(id);
    try {
      var doc = (iframe.contentDocument)? iframe.contentDocument: iframe.contentWindow.document;
      alert(doc.body.innerHTML);
    }
    catch(e) {
       alert(e.message);
    }
  return false;
}


<iframe id='iframe_id1' src="javascript:parent.somehtml()"> </iframe>
<br/>
<a href="#" onclick="return showIframeContent('iframe_id1')">Show</a>
<hr/>

<iframe id='iframe_id2' src="http://plungjan.name/"> </iframe>
<br/>
<a href="#" onclick="return showIframeContent('iframe_id2')">Show</a>
<hr/>
Run Code Online (Sandbox Code Playgroud)