Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the original innerHTML source without the Javascript generated contents?

Tags:

Is it possible to get in some way the original HTML source without the changes made by the processed Javascript? For example, if I do:

<div id="test">     <script type="text/javascript">document.write("hello");</script> </div> 

If I do:

alert(document.getElementById('test').innerHTML); 

it shows:

<script type="text/javascript">document.write("hello");</script>hello 

In simple terms, I would like the alert to show only:

<script type="text/javascript">document.write("hello");</script> 

without the final hello (the result of the processed script).

like image 223
Marco Demaio Avatar asked Dec 09 '10 11:12

Marco Demaio


1 Answers

I don't think there's a simple solution to just "grab original source" as it'll have to be something that's supplied by the browser. But, if you are only interested in doing this for a section of the page, then I have a workaround for you.

You can wrap the section of interest inside a "frozen" script:

<script id="frozen" type="text/x-frozen-html">

The type attribute I just made up, but it will force the browser to ignore everything inside it. You then add another script tag (proper javascript this time) immediately after this one - the "thawing" script. This thawing script will get the frozen script by ID, grab the text inside it, and do a document.write to add the actual contents to the page. Whenever you need the original source, it's still captured as text inside the frozen script.

And there you have it. The downside is that I wouldn't use this for the whole page... (SEO, syntax highlighting, performance...) but it's quite acceptable if you have a special requirement on part of a page.


Edit: Here is some sample code. Also, as @FlashXSFX correctly pointed out, any script tags within the frozen script will need to be escaped. So in this simple example, I'll make up a <x-script> tag for this purpose.

<script id="frozen" type="text/x-frozen-html">    <div id="test">       <x-script type="text/javascript">document.write("hello");</x-script>    </div> </script> <script type="text/javascript">    // Grab contents of frozen script and replace `x-script` with `script`    function getSource() {       return document.getElementById("frozen")          .innerHTML.replace(/x-script/gi, "script");    }    // Write it to the document so it actually executes    document.write(getSource()); </script> 

Now whenever you need the source:

alert(getSource()); 

See the demo: http://jsbin.com/uyica3/edit

like image 78
David Tang Avatar answered Nov 02 '22 14:11

David Tang