简体   繁体   中英

Obtaining HTML from the page in an iframe

I have created a screen which has two controls on it. The first one is an iframe which shows a web-page within the main web page. That works fine. Underneath that is a textarea in which I would like to display the HTML that created the iframe page. Here is an abstract of my HTML: How do I make this work?

<iframe id='myiframe'></iframe>
<textarea id='mybuffer'></textarea>

and

var cow = document.getElementById('myiframe');
var pig = document.getElementById('mybuffer');
cow.src='http:google.com'; //this works
pig.value=cow.innerHTML;   //this does not

The child would need to send the parent its html using the postMessage api . The parent would have an event listener where it waits for the child to send its html to it. The child can get its own html using

document.documentElement.outerHTML

once window.ondomready has fired.

The second part doesn't work because the document is not loaded yet, and because you are not getting the contents of the document but of the iframe itself (you say that both pages are in your server, if they were in different domains it won't work because you'll get a cross-origin error).

You have to wait until the main page is loaded, then load the frame, wait until the frame is loaded and then get the contents of the frame:

<head>
  <script type="text/javascript">
    function getFrameHTML() {
      var pig = document.getElementById('mybuffer');
      var cow = document.getElementById('myiframe');
      pig.value = cow.contentDocument.documentElement.outerHTML; //documentElement is <html>
    }

    function loadFrame() {
      var cow = document.getElementById('myiframe');
      cow.addEventListener("load",getFrameHTML);
      cow.src = 'http://YouHost/YourPage.html';
    }
  </script>
</head>

<body onload="loadFrame()">
  <iframe id="myiframe"></iframe>
  <textarea id="mybuffer"></textarea>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM