如何从iframe获取所有html字符串?

时间:2017-10-15 11:00:02

标签: javascript html

假设我有iframe包含sample.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="import" href="sample.html">
</head>

<body>
  <p>top</p>
  <iframe src="sample.html" frameborder="0" id="myframe"></iframe>
  <p>bottom</p>
  <textarea cols="30" rows="10"></textarea>
</body>

</html>

我希望所有内容都包含<!DOCTYPE html> ...</html>。我尝试搜索网络,但我发现只能使用

从身体获取内容
var cont = document.getElementById('myframe').contentWindow.document;
console.log(cont.body);

我不想使用AJAX来获取内容文件。 如何从iframe获取所有内容包括html标记?

3 个答案:

答案 0 :(得分:3)

尝试访问cont.documentElement.innerHTML以获取<html>代码的内容。

如果您还需要<html>标记,请使用cont.documentElement.outerHTML

要获取doctype信息,请尝试使用cont.doctype

var cont = document.getElementById('myframe').contentWindow.document;
console.log(cont.documentElement.outerHTML, cont.doctype);

如果浏览器支持XMLSerializer,您也可以使用{{3}}:

console.log(new XMLSerializer().serializeToString(cont));

答案 1 :(得分:1)

试试这个:

使用document.doctype获取文档doctype

使用document.getElementsByTagName("*");获取大部分html

https://jsfiddle.net/4hhf6nLm/

答案 2 :(得分:0)

以下行将检索iframe的内部html

  

的document.getElementById( 'myframe')。contentWindow.document.body.innerHTML

Check this answer for more information