1

In my project i have to retrieve the content in all script tags. I am able to do this by simply including

var scrpt=document.getElementsByTagName('script');
script_txt=scrpt[i].innerHTML;

but by using the above code i am not getting dynamic scripts which are created by

var s=document.createElement('script');
s.src="http://somefile.js";

not only this there are many other ways of creating dynamic scripts like

document.write('<script src="">'); 

and

document.body.innerHTML='<script src="">';

and many more. I tried to retrieve it by using regular expressions like this

var pattern=/([a-zA-Z0-9_\.].*?)=(document.createElement\((.*)\));
/g;

but this may not match all.

Can anyone suggest a better method for achieving this property.

4
  • i even tried this but this does not yield the dynamic script created Commented Apr 2, 2012 at 6:27
  • 2
    The main issue here is WHEN are you running the function to retrieve the scripts. There are scripts that will be fetch only after the user is clicking (e.g. Ads). So you want to make sure the triggers to your 'collecting' function is done after such events as well. Commented Apr 2, 2012 at 6:27
  • 2
    Do not use the innerHTML property, since script content isn't markup. Use the text property. Commented Apr 2, 2012 at 6:54
  • 2
    @dbaseman—document.scripts is an HTML5 feature and therefore not suitable on the general web since many browsers don't support it. Commented Apr 2, 2012 at 6:59

1 Answer 1

1

The first method you mentioned, using document.getElementsByTagName('script'), is fine.

I wrote up a fiddle where I'm counting script tags before and after inserting a tag dynamically. It works fine. http://jsfiddle.net/crGx9/

Could you show us an example of when it doesn't work?

Sign up to request clarification or add additional context in comments.

2 Comments

This works fine for your page. but imagine if you are counting scripts in other webpage for suppose you are extracting scripts from google.com by using userscripts then how can this be done
Have you made sure that you're not running inside an iframe for example? document.getElementsByTagName will only get tags from the same frame you're executing in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.