简体   繁体   English

在iframe中从页面获取HTML

[英]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. 第一个是iframe,它在主网页中显示一个网页。 That works fine. 很好 Underneath that is a textarea in which I would like to display the HTML that created the iframe page. 在下面是一个文本区域,我想在其中显示创建iframe页面的HTML。 Here is an abstract of my HTML: How do I make this work? 这是HTML的摘要:如何进行这项工作?

<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 . 子级需要使用postMessage api向其父级发送html。 The parent would have an event listener where it waits for the child to send its html to it. 父级将有一个事件侦听器,它在其中等待子级将其html发送给它。 The child can get its own html using 孩子可以使用以下方式获取自己的html:

document.documentElement.outerHTML

once window.ondomready has fired. 一旦window.ondomready触发。

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). 第二部分不起作用,因为尚未加载文档,并且因为您没有获得文档的内容,而是iframe本身的内容(您说这两个页面都在服务器中,如果它们位于不同的域中,则它将赢得)无效,因为您会收到跨域错误)。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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