Joshua
Joshua

Reputation: 6833

Displaying Source Of Javascript Code

I would like to accomplish something like:

<html>
  <head>
    <script id="ViewSource" src="someJSfile.js"/>
    <script language="javascript">
      function View() {
        var el=document.getElementById("ViewSource"); //works
        var ta=document.getElementById("ta");         //works
        ta.value=el.innerHTML;                        //doesn't work
      }
    </script>
  </head>
  <body>
    <textarea id="ta"/>
    <a href="javascript:View();">View Javascript Source Code</a>
  </body>
</html>
// (please pardon any typos/errors, the above is just to illustrate what I mean)

Of course "innerHTML" doesn't work on script tags. What property/attribute can I access to view source?

I realize this can be accomplished very easily by just clicking view source in the browser. Am I crazy to hope it can be done with javascript?

Thanks in advance.

Upvotes: 1

Views: 207

Answers (3)

Christian Joudrey
Christian Joudrey

Reputation: 3461

Why don't you just fire an AJAX call and download the "someJSFile.js"? Once you downloaded it you would have access to it in a JS variable.

If you are using jQuery this can easily be done using $.get: http://api.jquery.com/jQuery.get/

Edit: In theory it shouldn't even re-download the file since it is cached in the browser (depends on your server settings and the browser settings).

  • Christian

Upvotes: 3

jcomeau_ictx
jcomeau_ictx

Reputation: 38412

If you set ta.innerHTML = el.innerHTML, it would at least have a chance of working.


<a href="http://www.google.com">bleah
<script id="thescript" type="text/javascript">
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
 if (links[i].href == "http://www.google.com/") links[i].href = "http://www.blather.blorg/"
}
</script>
<br clear="all" />
<textarea id="view">
</textarea>
<script type="text/javascript">
document.getElementById("view").innerHTML =
 document.getElementById("thescript").innerHTML;
</script>

The above seems to work, except I need to expand the size of the textarea to view all of it.

Upvotes: 0

James Kovacs
James Kovacs

Reputation: 11651

Try this:

  function View() {
    var el=document.getElementById("ViewSource"); //works
    var ta=document.getElementById("ta");         //works
    ta.value=el.text;                             //works!
  }

Upvotes: 0

Related Questions