tags:

views:

98

answers:

3

Possible Duplicate:
What is my script src URL?

I have situation:

<script 
  type="text/javascript" 
  src="http://server/some.js"&gt;
</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).

A: 

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

function getScriptFileName() {
  return (new Error).fileName;
}
silent
Sadly no, the `Error` object is unstandardised and `fileName` only seems to exist in Mozilla.
bobince
+5  A: 

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
+1, very nice approach.
Darin Dimitrov
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 = 0and s. Nice piece of code, otherwise.
Tom Bartel
Tom Bartel - you were rightfixed and thx for the tip on that
tomaszsobczak
+1  A: 

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