documentElement[removed] not showing the iframe bo

2019-08-02 20:42发布

问题:

i have got a page that has one iframe in it. i am making the iframe via javascript. later i need to save that page and reopen it with the exact contents. like e.g if the user wrote sumthing in the iframe body and saved it and then reopened the page, the iframe shud hav the same contents. to save the page my logic is to get the document's innerHTML, create a new html file and write the contents to it. now the prblm is that when i do document.documentElement.innerHTML , the iframe section does appear in it, but the body section and the html section is missing. the only thing that appears is <iframe></iframe>. how can i get HTML of iframe along with the parent page's HTML? heres the code to let u see what document.documentElement.innerHTML prints on the console

<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>

im using this in chrome... thanks!!

回答1:

Based on this post, here a solution:

UPDATE

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);
}

At least it works with my Chrome browser (Version 11.0.696.60)