10

Possible Duplicate:
What is my script src URL?

I have situation:

<script 
  type="text/javascript" 
  src="http://server/some.js">
</script>

In file some.js I need to know full path of same file some.js, eq. "http://server/some.js". How can I do this?

I can't change HTML code (clients are including JS file).

Community
  • 1
  • 1

3 Answers3

9

try that one

sc = document.getElementsByTagName("script");

for(idx = 0; idx < sc.length; idx++)
{
  s = sc.item(idx);

  if(s.src && s.src.match(/some\.js$/))
  { return s.src; }
}
TomaszSobczak
  • 2,900
  • 21
  • 24
  • 3
    Tomasz, am I missing something or where do you initialise sc? Also, IMO the whole thing is cleaner if you add the var keyword before idx = 0 and s. Nice piece of code, otherwise. – Tom Bartel Nov 10 '09 at 09:24
  • Tom Bartel - you were right fixed and thx for the tip on that – TomaszSobczak Nov 10 '09 at 09:27
  • without `var idx=0` in the for loop you will introduce a global idx variable (unless you previously defined `idx` with `var`) – Russ Feb 16 '15 at 17:10
9

The simplest way is just to look for the last script to be added to the document:

var scripts= document.getElementsByTagName('script');
var mysrc= scripts[scripts.length-1].src;

This has to be done in the main body of the script, not in code called later. Preferably do it at the start of the script and remember the variable so it can be used in later function calls if necessary, and so it's not affected by code later in the script inserting any new <script> nodes into the document.

bobince
  • 528,062
  • 107
  • 651
  • 834
0

Not sure it works in all browsers, by try this:

function getScriptFileName() {
  return (new Error).fileName;
}
silent
  • 3,843
  • 23
  • 29