【问题标题】:Getting the source code of an iframe获取 iframe 的源代码
【发布时间】:2011-01-19 01:23:38
【问题描述】:

是否可以获取 iframe 加载的页面的源代码?我不想更改任何代码,我只想阅读它。我还需要能够使用 javascript/html 来获取它。

【问题讨论】:

  • 我正在通过 google 扩展程序执行此操作。我在“权限”下添加了我试图访问清单文件的域。我不完全确定这是否解决了相同的域问题,但假设域相同,你会怎么做?
  • <iframe id="fbfr" src="http://www.facebook.com/friends/"></iframe><script>steal_your_infos(fbfr.document.innerHTML);</script>
  • 您可能会发现这很有用:stackoverflow.com/questions/364952/…

标签: javascript html iframe


【解决方案1】:
document.getElementById('iframeID').contentWindow.document.body.innerHTML

适用于 Firefox、Chrome、Opera、IE9 beta

【讨论】:

  • @Daz 浏览器报错了吗?在 Chrome 中尝试一下,因为该浏览器具有良好的错误报告功能。如果是跨域问题,Chrome 会在错误中说明。
  • 我正在通过 chrome 运行它。它在那条线上崩溃。我在后面的线路上放了一条警报,但警报没有触发。我已经看到了这种工作的例子,但它们是从 2008 年开始的。你确定这仍然适用于现代浏览器吗?
  • @Daz 是的,但是打开控制台(右键单击 -> 检查元素)。它将向您显示有关错误的详细信息。
  • 我收到这个错误“Uncaught TypeError: Cannot read property 'body' of undefined”
  • @Daz 这意味着您未能获得 IFRAME 元素。请不要告诉我你只是复制粘贴了我的代码。 :) 您必须将 iframeID 替换为 IFRAME 元素的 ID 属性。
【解决方案2】:

试试这样:

<!DOCTYPE html>
<html>
<body>

//this is iframe I ll look for its source
<iframe id="frmin" src="http://www.w3schools.com"></iframe>

<p>Click the button to see the source.</p>
//this is display I will display Iframe's source here
<div id="srcout"></div>

//show source upon click event
<button onclick="myFunction()">Show it</button>

<script>
function myFunction() {
//get Iframe element ready for javascript manipulation
var frm = document.getElementById("frmin");
//get display element ready for javascript manipulation
var dsp = document.getElementById("srcout");

//find Iframe's HTML (root) element, [0] because I'm using getElementsByTagName which returns node list so I have to chose the 1st one, and put its outer content (i.e. with outer tags) to display, i.e. dsp.innerText. I use innerText because I want a text output not formatted as html.
dsp.innerText = frm.contentDocument.getElementsByTagName('html')[0].outerHTML;

}
</script>

</body> 
</html>

【讨论】:

  • 此方法使用获取 iframe 的 HTML 元素
  • 这种方法使用获取 Iframe 的 HTML 元素。首先,我使用 Iframe 特定操作 document.getElementById("frmin").contentDocument... 来访问 Iframe 的内容...然后我使用 getElementsByTagName 来查找 Iframe 的 HTML(根)元素:。 ..contentDocument.getElementsByTagName('html')[0]... // ('html')[0] 如果有更多的 HTML 元素。最后,我使用 ...outerHTML... 来获取 HTML 代码,包括。外部标签。
  • 请在您的帖子中添加解释;谢谢!
【解决方案3】:

我知道这看起来很复杂,但我为您提供了一种 100% 防弹的方法,可以在您的页面上查看您的源代码。 我不完全知道如何在 iframe 中显示它,但是还有另一种查看源代码的方法,它比 iframe 好得多,就是这样。

重要的是JavaScript和HTML完全一样。

CSS:&lt;head&gt;&lt;/head&gt; 部分:

<style type="text/css" >
.button
    {
    background:#000cff;
    padding:2px 10px;
    color:white;
    text-decoration:none;
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
    border-radius:10px;
    cursor: pointer;
    font-weight: bold;
    color: white;
    display: inline-block;
    box-shadow: 0 0 3px gray;
    margin: 0px;
    font: bold 11px Arial, Sans-Serif;
    }

#source-code
    {
    display:none;
    position:absolute;
    top:-24px;
    left:0;
    width:100%;
    height:414px;
    background:rgba(255,255,255,0.0);
    }

#source-code:target { display: block; }
#source-code pre
    {
    padding:20px;
    font:14px/1.6 Monaco, Courier, MonoSpace;
    margin:50px auto;
    background:rgba(0,0,0,0.8);
    color:white;
    width:80%;
    height:80%;
    overflow:auto;
    }

#source-code pre a,
#source-code pre a span
    {
    text-decoration:none;
    color:#00ccff !important;
    }

#x
    {
    position:absolute;
    top:30px;
    left:10%;
    margin-left:-41px;
    }

.control-copytextarea
    {
    position:absolute;
    top:-3px;
    left:20px;
    cursor: pointer;
    font-weight: bold;
    padding:3px 10px;
    border-radius: 5px 5px 0 0;
    background: darkred;
    color: white;
    display: inline-block;
    box-shadow: 0 0 3px gray;
    margin: 0px;
    font: bold 10px Arial, Sans-Serif;
    }
</style>

JavaScript:

<script languade="JavaScript">
        $(function() {
            $("<pre />", {
                "html":   '&lt;!DOCTYPE html>\n&lt;html>\n' + 
                        $("html")
                            .html()
                            .replace(/[<>]/g, function(m) { return {'<':'&lt;','>':'&gt;'}[m]})
                            .replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,'<a href="$1">$1</a>') + 
                        '\n&lt;/html>',
                "class": "prettyprint"
            }).appendTo("#source-code");

            prettyPrint();
        });
</script>

<script languade="JavaScript">
        var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
        document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>

<script languade="JavaScript">
        var pageTracker = _gat._getTracker("UA-68528-29");
        pageTracker._initData();
        pageTracker._trackPageview();
</script>

注意: 您不需要从在线使用这些 JavaScript 代码,但为了让它在所有浏览器上都能正常工作,建议您也使用它们。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://css-tricks.com/examples/ViewSourceButton/prettify/prettify.js"></script>

HTML:&lt;body&gt;&lt;/body&gt;部分:

<a class="button" href="#source-code" id="view-source">Show the Source Code for this page</a>
<div id="source-code" align="left">
    <a href="#" id="x"><input type="button" alt="close" class="control-copytextarea" value=" Close Source Code Viewing " /></a>
</div>

注意:您可以直接将代码复制并粘贴到您的网页,它会完全按照原样工作。

完整示例:

<html>
  <head><title>View your Source Code</title>

<style type="text/css" >
.button
    {
    background:#000cff;
    padding:2px 10px;
    color:white;
    text-decoration:none;
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
    border-radius:10px;
    cursor: pointer;
    font-weight: bold;
    color: white;
    display: inline-block;
    box-shadow: 0 0 3px gray;
    margin: 0px;
    font: bold 11px Arial, Sans-Serif;
    }

#source-code
    {
    display:none;
    position:absolute;
    top:-24px;
    left:0;
    width:100%;
    height:414px;
    background:rgba(255,255,255,0.0);
    }

#source-code:target { display: block; }
#source-code pre
    {
    padding:20px;
    font:14px/1.6 Monaco, Courier, MonoSpace;
    margin:50px auto;
    background:rgba(0,0,0,0.8);
    color:white;
    width:80%;
    height:80%;
    overflow:auto;
    }

#source-code pre a,
#source-code pre a span
    {
    text-decoration:none;
    color:#00ccff !important;
    }

#x
    {
    position:absolute;
    top:30px;
    left:10%;
    margin-left:-41px;
    }

.control-copytextarea
    {
    position:absolute;
    top:-3px;
    left:20px;
    cursor: pointer;
    font-weight: bold;
    padding:3px 10px;
    border-radius: 5px 5px 0 0;
    background: darkred;
    color: white;
    display: inline-block;
    box-shadow: 0 0 3px gray;
    margin: 0px;
    font: bold 10px Arial, Sans-Serif;
    }
</style>

<script languade="JavaScript">
        $(function() {
            $("<pre />", {
                "html":   '&lt;!DOCTYPE html>\n&lt;html>\n' + 
                        $("html")
                            .html()
                            .replace(/[<>]/g, function(m) { return {'<':'&lt;','>':'&gt;'}[m]})
                            .replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,'<a href="$1">$1</a>') + 
                        '\n&lt;/html>',
                "class": "prettyprint"
            }).appendTo("#source-code");

            prettyPrint();
        });
</script>

<script languade="JavaScript">
        var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
        document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>

<script languade="JavaScript">
        var pageTracker = _gat._getTracker("UA-68528-29");
        pageTracker._initData();
        pageTracker._trackPageview();
</script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script src="http://css-tricks.com/examples/ViewSourceButton/prettify/prettify.js"></script>

  </head>
<body>



<a class="button" href="#source-code" id="view-source">Show the Source Code for this page</a>
<div id="source-code" align="left">
    <a href="#" id="x"><input type="button" alt="close" class="control-copytextarea" value=" Close Source Code Viewing " /></a>
</div>


  </body>
</html>

【讨论】:

    【解决方案4】:

    请参阅https://developer.mozilla.org/en/HTML/Element/iframe#Scripting,了解基于 Mozilla 的浏览器如何处理它。你最喜欢的 JavaScript 库中应该有抽象,可以处理 IE、WebKit、Gecko 等 DOM 之间不可避免的命名差异。

    【讨论】:

      【解决方案5】:

      使用 JQuery:http://api.jquery.com/contents/(仅当域匹配时)

      例如:

      $(iframe).contents().find('body').html();
      

      如果不匹配,您可以再次加载它(因为它可能已经存储在客户端中,它可能不会再次进入服务器):

      var html;
      $.get($(iframe).get(0).src, function(content) {
          html = content;
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-21
        • 1970-01-01
        • 2011-11-29
        • 2014-03-24
        • 1970-01-01
        相关资源
        最近更新 更多