12

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.

Franz Payer
  • 4,069
  • 15
  • 53
  • 77
  • 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 Jan 19 '11 at 01:28
  • `` – drudge Jan 19 '11 at 01:35
  • you might find this to be useful: http://stackoverflow.com/questions/364952/jquery-javascript-accessing-contents-of-an-iframe – jpwco Jan 19 '11 at 01:35

5 Answers5

2
document.getElementById('iframeID').contentWindow.document.body.innerHTML

Works in Firefox, Chrome, Opera, IE9 beta

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • @Daz Does the browser report an error? Try it out in Chrome, since that browser has good error reporting. If it's a cross-domain issue, Chrome will tell that in the error. – Šime Vidas Jan 19 '11 at 01:43
  • I am running it through chrome. It crashes on that line. I put an alert the line after and the alert doesnt trigger. I have seen examples of this working but they were from 2008. Are you sure this still works on modern browsers? – Franz Payer Jan 19 '11 at 01:44
  • @Daz Yes, but open the console (right click -> Inspect element). It will show you the details about the error. – Šime Vidas Jan 19 '11 at 01:46
  • I am getting this error "Uncaught TypeError: Cannot read property 'body' of undefined" – Franz Payer Jan 19 '11 at 01:53
  • @Daz You'll have to use the console to figure this out. You can execute this: `console.log(document.getElementById('iframeID').contentWindow)`. This will print out the window object of the iframed web-page. – Šime Vidas Jan 19 '11 at 01:57
  • 1
    @Daz That means you failed to get the IFRAME element. Please don't tell me that you just copy-pasted my code. `:)` You have to replace `iframeID` with the ID attribute of your IFRAME element. – Šime Vidas Jan 19 '11 at 02:02
  • ohh, sorry. now im getting "undefined" even though i can clearly see that the iframe loaded something. it also says "Unsafe JavaScript attempt to access frame with URL http://www.google.com from frame with URL file:///D:/Users/User/Desktop/Chrome%20extension/popup.html. Domains, protocols and ports must match." – Franz Payer Jan 19 '11 at 02:03
  • >console.log(document.getElementById('frame').contentWindow) Object true – Franz Payer Jan 19 '11 at 02:07
  • @Daz You know what that means, right? The Same Origin Policy does not allow you to read the window object of the iframed page. – Šime Vidas Jan 19 '11 at 02:09
  • ...that's what I am trying to do – Franz Payer Jan 19 '11 at 02:12
  • @Daz Your question is: How to bypass the Same Origin Policy? There are questions on SO that address that problem: http://stackoverflow.com/search?q=bypass+same+origin+policy – Šime Vidas Jan 19 '11 at 02:14
0

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>
Lumic
  • 61
  • 2
  • This approach uses getting Iframe's HTML element – Lumic Oct 20 '15 at 21:29
  • This approach uses getting Iframe's HTML element. First I use Iframe specific manipulation **document.getElementById("frmin").contentDocument...** to access Iframe's content... then I use getElementsByTagName to find Iframe's HTML (root) element: **...contentDocument.getElementsByTagName('html')[0]...** // ('html')[0] if there were more HTML elements. Finally, I use **...outerHTML...** to get HTML code incl. outer tags. – Lumic Oct 20 '15 at 21:38
  • Please add the explanations to your post; thank you! – aschipfl Oct 20 '15 at 21:40
0

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>
SeekLoad
  • 973
  • 1
  • 9
  • 33
0
    <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

-2

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.

wmorrell
  • 4,988
  • 4
  • 27
  • 37