2

I have a web site which downloads the same script from any number of different servers:

<script type="text/javascript" src="http://server1.example.com/hello.js"></script>
<script type="text/javascript" src="http://server2.example.com/hello.js"></script>
<script type="text/javascript" src="http://server3.example.com/hello.js"></script>
<script type="text/javascript" src="http://server4.example.com/hello.js"></script>

Each script has a locally-scoped variable which has to be the hostname of the server that script was downloaded from: so when I download the script from server1.example.com that variable's value has to be server1.example.com.

Can this be done with absolutely no server-side programming? (AJAX requests can be sent, but the solution cannot include any server-side code)

Please note that I am looking for the host which the script is hosted on, not the host of the current browser page; that means I am not looking for window.location.

Richard JP Le Guen
  • 28,364
  • 7
  • 89
  • 119
  • Duplicate of http://stackoverflow.com/questions/710957/how-might-i-get-the-script-filename-from-within-that-script. See that question for a good answer. – Elliot Nelson Sep 28 '11 at 13:48
  • @Elliot Nelson; close but no cigar; some of my ` – Richard JP Le Guen Sep 28 '11 at 13:59

2 Answers2

1

I think the below code can help:

var scripts = document.getElementsByTagName('script');
for(var a = 0; a < scripts.length; a++){
    if(scripts[a].src.indexOf('<<<--###-->>>') > 0 ) 
        var ThisScriptPath = scripts[a].src.substr( 0, scripts[a].src.lastIndexOf('/'));
}

You will need to replace the <<<--###-->>> with your script's name, and you will have the path stored in ThisScriptPath (remember to use the final slash)

Tip: Use an alert to check the results before getting into production

RKdevs.com
  • 11
  • 1
  • using lastIndexOf won't give you necessarily the hostname, since the URL might be: http://hostname.com/js/directory/file.js (so the script would give you http://hostname.com/js/directory – manavo Jun 27 '13 at 23:19
-3

You can extract from window.location.host the first part of the domain name with regex.

You can use that in order to extract the first part

var host = window.location.host;
host = host.match(/^[\d\w]+/);
KodeFor.Me
  • 13,069
  • 27
  • 98
  • 166
  • Sorry @Merianos Nikos, but this is not what I'm looking for, and even if it were, using `window.location.hostname` would be a better idea than using a RegEx. See [MDN's window.location reference](https://developer.mozilla.org/en/window.location#Properties) for the properties of `window.location`. – Richard JP Le Guen Sep 28 '11 at 14:03
  • this would be the URL of the webpage and not of the script, if script is added from cross domain. – Anuj Pandey Dec 02 '13 at 11:29