views:

119

answers:

2

Is it possible from a Javascript code to find out "where" it came from?

I needed this to provide scripts that could run folder-agnostic, e.g.:

http://web1/service-a/script.js
http://web2/some-folder/service-b/script.js

And they're linked in:

http://web1/page1.html
http://web2/page2.html

The file script.js is identical in both locations but I would like them to be able to find out where it originates from so it can call the right web service methods (script.js from service-a should call service-a.method while script.js that is served from service-b should call service-b.method)

Is there a way to find out where script.js came from without using any server-side code?

+2  A: 

You can analyze source of the html where script.js is included for tag and retrieve path of the script.js from there. Include next function in script.js and use it to retrieve the path.

function getPath() {
   var path = null;
   var scriptTags = document.getElementsByTagName("script");

   for (var i = 0; i < scriptTags.length; i++) {
      var scriptTagSrc = scriptTags.item(i).src;

      if (scriptTagSrc && scriptTagSrc.indexOf("script.js") !== -1) {
          path = scriptTagSrc;
          break;
      }
   }

   return path;
}
Svitlana Maksymchuk
+2  A: 

Well, it's kind of a hack, you could grab all the <script> tags in the document, look at which one has the file name of the file, and do the logic from there.

document.getElementsByTagName('script'); is pretty much all you need. The rest is basic JS.

Even more interesting than looping through all of the returned elements (although that's probably safest), is that we can simply only look at the last element returned by the call above, as Javascript guarantees that must be the <script> tag we're in at the time of it being parsed (with the exception of deferred scripts). So this code:

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

Will alert the source of the script tag used to include the current Javascript file.

Paolo Bergantino
I imagine it wouldn't work in IE.... but let's try it anyway :-P
chakrit
Let me know how it goes. :)
Paolo Bergantino