是否可以使用Javascript检索iframe的* full * HTML页面源?

时间:2013-06-09 04:09:02

标签: javascript jquery dom iframe doctype

我正在尝试弄清楚如何从<iframe> src检索完整(即所有数据)HTML网页来源来自与其嵌入的页面相同的原始域。我想在任何给定时间获得确切的源代码,由于Javascript或php生成<iframe> html输出,因此可能是动态的。这意味着像$.get()这样的AJAX调用对我来说不起作用,因为页面可能是通过Javascript修改的,或者是基于请求时间或php中的mt_rand()唯一生成的。我无法从我的<!DOCTYPE>检索确切的<iframe>声明。

我一直在尝试并搜索Stack Overflow并且找不到可以检索所有页面源的解决方案,包括<!DOCTYPE>声明。

How do I get the entire page's HTML with jQuery?中的一个答案表明,为了检索<!DOCTYPE>信息,您需要通过检索<iframe>的{​​{1}}来手动构建此声明属性,然后自己将所有属性添加到document.doctype声明。这真的是从<!DOCTYPE>的HTML页面源检索此信息的唯一方法吗?

以下是我看过的一些值得注意的Stack Overflow帖子,这不是重复的:

以下是我的一些本地测试代码,它说明了我迄今为止的最佳尝试,它只检索<iframe>的{​​{1}}标记内的数据:

main.html中

<iframe>


Iframe.html的

<html>


这些文件的屏幕截图在Google Chrome版本27.0.1453.110 m中一起运行: iframe testing

摘要

正如您所看到的,Google Chrome浏览器的<html> <head> <title>Testing with iframe</title> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script type="text/javascript"> function test() { var doc = document.getElementById('iframe-source').contentWindow.document; var html = $('html', doc).clone().wrap('<p>').parent().html(); $('#output').val(html); } </script> </head> <body> <textarea id="output"></textarea> <iframe id="iframe-source" src="iframe.html" onload="javascript:test()"></iframe> </body> </html> 显示<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html class="html-tag-class"> <head class="head-tag-class"> <title>iframe Testing</title> </head> <body class="body-tag-class"> <h2>Testing header tag</h2> <p>This is <strong>very</strong> exciting</p> </body> </html> Inspect element声明中存在,因此如何使用页面源检索此数据?此问题也适用于<iframe>标记中未包含的任何其他声明或其他标记。


任何有关通过Javascript检索此完整页面源代码的帮助或建议都将非常感激。

1 个答案:

答案 0 :(得分:2)

这是一种从doctype构建它的方法,似乎适用于html 4和5,我没有测试像svg这样的东西。

<html>
<head>
  <title>Testing with iframe</title>
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <script type="text/javascript">
  function test() {
    var d = document.getElementById('iframe-source').contentWindow.document;
    var t = d.docType;
    $('#output').val(
        "<!DOCTYPE "+t.name+ 
          (t.publicId? (" PUBLIC "+JSON.stringify(t.publicId)+" ") : "")+
          (t.systemId? JSON.stringify(t.systemId) :"")+
          ">\n" + d.documentElement.outerHTML  );
  }
  </script>
</head>
<body>

<textarea id="output"></textarea>
<iframe id="iframe-source" src="iframe.html" onload="test()"></iframe>

</body>
</html>

这也使用HTML.outerHTML来确保你获得documentElement的任何属性。