最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting the source code of an iframe - Stack Overflow

programmeradmin10浏览0评论

Is there anyway to get the source code of the page that an iframe loaded? I do not wish to CHANGE any of the code, I just want to READ it. I also need to be able to get this using javascript/html.

Is there anyway to get the source code of the page that an iframe loaded? I do not wish to CHANGE any of the code, I just want to READ it. I also need to be able to get this using javascript/html.

Share Improve this question asked Jan 19, 2011 at 1:23 Franz PayerFranz Payer 4,13716 gold badges55 silver badges77 bronze badges 3
  • I am doing this through a google-extension. I added the domain I am trying to access to the manifest file under "permissions". I not entirely sure if this gets past the same domain problem, but how would you do it assuming the domains are the same? – Franz Payer Commented Jan 19, 2011 at 1:28
  • <iframe id="fbfr" src="http://www.facebook.com/friends/"></iframe><script>steal_your_infos(fbfr.document.innerHTML);</script> – jrn.ak Commented Jan 19, 2011 at 1:35
  • you might find this to be useful: stackoverflow.com/questions/364952/… – jpwco Commented Jan 19, 2011 at 1:35
Add a comment  | 

5 Answers 5

Reset to default 3
document.getElementById('iframeID').contentWindow.document.body.innerHTML

Works in Firefox, Chrome, Opera, IE9 beta

Try it like this:

<!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>

I know it looks complicated but I am giving you a 100% bullet proof way that works to view your source codes on your page. I do not exactly know how to show it in iframes, but there is another way to view source codes witch is much better then iframes and this is how.

What is important is the JavaScript and the HTML is exactly like this.

CSS: In the <head></head> section:

<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>

NOTE: You do not need to use these JavaScript codes from online, but for the sake of having it work on all browsers it is advised you use them too.

<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: In the <body></body> section:

<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>

NOTE: You can directly copy and paste the codes to your webpage, it will work exactly as it is.

Full EXAMPLE:

<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>
    <html>
      <head>
<title>source code viewer</title>
 <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://CodeMirror.net/addon/hint/anyword-hint.js" id="anyword"></script>
<link rel="stylesheet" href="https://CodeMirror.net/lib/codemirror.css">
<link rel="stylesheet" href="https://CodeMirror.net/theme/DE.css">
<link rel="stylesheet" href="https://CodeMirror.net/addon/hint/show-hint.css">
<link rel="stylesheet" href="https://CodeMirror.net/addon/dialog/dialog.css">
<link rel="stylesheet" href="https://CodeMirror.net/addon/search/matchesonscrollbar.css">
<script src="https://CodeMirror.net/lib/codemirror.js"></script>
<script src="https://CodeMirror.net/addon/edit/closetag.js"></script>
<script src="https://CodeMirror.net/addon/hint/show-hint.js"></script>
<script src="https://CodeMirror.net/addon/hint/sql-hint.js"></script>
 <script src="https://CodeMirror.net/addon/mode/loadmode.js"></script>
<script src="https://CodeMirror.net/mode/meta.js"></script>
<script src="https://CodeMirror.net/addon/hint/xml-hint.js"></script>
<script src="https://CodeMirror.net/addon/hint/html-hint.js"></script>
<script src="https://CodeMirror.net/addon/search/jump-to-line.js"></script>
<script src="https://CodeMirror.net/addon/hint/javascript-hint.js"></script>
<script src="https://CodeMirror.net/mode/xml/xml.js"></script>
<script src="https://CodeMirror.net/mode/javascript/javascript.js"></script>
<script src="https://CodeMirror.net/mode/css/css.js"></script>
<script src="https://CodeMirror.net/mode/htmlmixed/htmlmixed.js"></script>
<script src="https://CodeMirror.net/addon/dialog/dialog.js"></script> 
<script src="https://CodeMirror.net/addon/search/searchcursor.js"></script>
<script src="https://CodeMirror.net/addon/search/jump-to-line.js"></script> 
<script src="https://CodeMirror.net/addon/search/search.js"></script> 
<script src="https://CodeMirror.net/addon/scroll/annotatescrollbar.js"></script> 
<script src="https://CodeMirror.net/addon/search/matchesonscrollbar.js"></script>
    <style>
    
    #window{
            margin-left:-22px;
            margin-top: -40px;
            border: none;
            width:394px;
            height:660px;
            }
    .preview-nav{
            margin-left:-33px;
            margin-top:-100px;
            background: #00002c;
            position: fixed;
            height:62px;
            width:415px;
            }
    .Run{
      z-index:3;
      display:none;
      padding-top:100px;
      position:fixed;
      left:0;
      top:0;
      width:100%;
      height:100%;
      overflow:auto;
      background-color:#ffffff;
      }
    .Run-content{
      border-radius:8px;
      margin:auto;
      background-color:#ffffff;
      position:relative;
      padding:0;
      outline:0;
      width:350px;
      height:300px;
      color:#000000;
      }
      .ncolor{
        background: none;
        border: none;
      }
      .cm-keyword{
        color: red;
      }
    </style>
      </head>
      <body bgcolor="#000000">
        <table border="0">
        <tr><td><input type="url" autocomplete="off" id="url" placeholder="URL...." oninput="Get()"></td><td><button onclick="document.getElementById('Run').style.display='block'" style="margin-top:-50px;" class="bbotton"><img src="icons/browser.png" width="45" height="45"></button></td><td><button class="Save" onclick="Save()"><img src="icons/GDownload.png" width="50" height="48"></button></td></tr>
        </table>
        <div id="SourceCode" onclick="editor.execCommand('autocomplete')"></div>
        <div id="tools">
          <button style="margin-top:-46px;margin-left:30px;position:fixed;" class="ncolor" onclick="find()"><img src="icons/search.png" width="40" height="40"></button>
          </div>
        <script>
          var editor = CodeMirror(document.getElementById('SourceCode'), {
            mode: 'text/html',
            lineNumbers: true,
            theme: 'DE',
          });
        </script>
    <script>
    function viewsource() {
    
      editor.setValue(document.getElementById('window').contentWindow.document.documentElement.innerHTML);
    }
    function Get() {
    
    document.getElementById('window').src= document.getElementById('url').value;
    }
    function Save() {
        var textToWrite = editor.getValue();
        var textFileAsBlob = new Blob([textToWrite], {
            type: ''
        });
        var fileNameToSaveAs = document.getElementById('url').value;
        var downloadLink = document.createElement("a");
        downloadLink.download = fileNameToSaveAs;
        downloadLink.innerHTML = "Download File";
        if (window.webkitURL && window.webkitURL.createObjectURL) {
            // Chrome allows the link to be clicked
            // without actually adding it to the DOM.
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
        } else {
            // Firefox requires the link to be added to the DOM
            // before it can be clicked.
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
            downloadLink.onclick = destroyClickedElement;
            downloadLink.style.display = "none";
            document.body.appendChild(downloadLink);
        }
        downloadLink.click();
    }
    
    function destroyClickedElement(event) {
        document.body.removeChild(event.target);
    }
    function find() {
      
      editor.execCommand('find');
    }
    function AC() {
      
      editor.execCommand('autocomplete');
    }
    </script>
         <div id="Run" class="Run">
      <div class="Run-content">
        <div>
     <nav class="preview-nav">
    <button class="ncolor" onclick="document.getElementById('Run').style.display='none';"><img src="icons/Close.png" width="50" height="50"></button>
    </nav>
           <iframe id="window" onload="viewsource()" onerror="error()"></iframe>
         </div>
        </div>
       </div>
      </body>
    </html>

But the source cannot be displayed unless the file to be downloaded is located locally on the device, for example:- If you try It will not work because for security purposes the contents of the window can only be accessed if the file to be included is located locally on the device

See https://developer.mozilla.org/en/HTML/Element/iframe#Scripting for how Mozilla-based browsers handle it. There should be abstractions in Your Favorite JavaScript Library that will handle the inevitable naming differences between IE, WebKit, Gecko, etc DOMs.

发布评论

评论列表(0)

  1. 暂无评论