documentElement.innerHTML不显示iframe主体



我有一个页面,其中有一个iframe。我通过javascript制作iframe。稍后,我需要保存该页面,并重新打开它与确切的内容。例如,如果用户在iframe主体中写了一些东西并保存了它,然后重新打开了页面,那么iframe应该具有相同的内容。为了保存页面,我的逻辑是获取文档的innerHTML,创建一个新的html文件并将内容写入其中。现在的问题是,当我做document.documentElement.innerHTML, iframe部分确实出现在它,但身体部分和html部分缺失。唯一出现的是<iframe></iframe>。我怎么能得到iframe的HTML随着父页面的HTML?下面的代码可以让你看到document.documentElement.innerHTML在控制台

上打印的内容
<html>
<head>
   <title>iframe test</title>
<script type="text/javaScript">
function showStr(){
        var customArea = document.getElementById('custom-area');
        var newdiv = document.createElement('div'); 
        newdiv.setAttribute('id',"myDiv");
        customArea.appendChild(newdiv);
        var htcontents = "<iframe id='myIframe' frameborder='1'></iframe>";
        newdiv.innerHTML = htcontents; 
        document.getElementById("myIframe").contentDocument.designMode="on";
}
function showIF()
{
    console.log(document.documentElement.innerHTML);
}
</script>
</head>
<body onLoad="showStr()">
<button id="myButton" onClick="showIF()"></button>
<div id="custom-area"></div>
</body>
</html>

我在chrome中使用这个…谢谢! !

基于这篇文章,这里有一个解决方案:

function showIF()
{
  var f= document.getElementById('myIframe');
  var d= f.contentDocument? f.contentDocument : f.contentWindow.document;
  var customArea = document.getElementById('custom-area');
  //read the content of iframe
  var iframeContent = d.body.innerHTML;
  //delete the iframe himself
  f.parentNode.removeChild(f);
  //Append the html to parent div
  customArea.innerHTML += iframeContent;
  //console.log(d.body.innerHTML);
}

至少它可以与我的Chrome浏览器(版本11.0.696.60)

最新更新