How to make an external javascript file knows its own host?

advertisements

Is there any way that in an external javascript file, can know the host of the file?

For example, if I have the site http://hostOne.com/index.php, the code of the file index.php:

<html>
<head>
   <script type="text/javascript" src="http://hostTwo.com/script/test.js"></script>
</head>
<body>
   <div>...</div>
</body>
</html>

I need that in the file test.js can know the host http://hostTwo.com.

Thank you.

EDIT

or it can know the tag "script" which was called?, with this option I can analyzes the tag and get the "src" attribute. But I don't want to depend on the name of the file test.js and analyze all the tag script that contains the site.

*Solution based on the code of @Armi *

Html:

    <html>
    <head>
      <script class="jsbin"  src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
      <script id="idscript" type="text/javascript" src="http://hostTwo.com/script/test.js"></script>
    </head>
    <body>
       <div>...</div>
    </body>
    </html>

code in JS

var
     url = $('head').find('#idscript').attr('src'),
     host = url.replace(/(\/\/.*?\/).*/g, '$1');

console.log(host);


I've got an idea (the snippet based on jQuery):

var yourScriptTag = $('head').find('script[src$="jquery-1.7.1.js"]').eq(0);
var theHostnameOfYourScript = $(yourScriptTag).attr('src').replace(/(http:\/\/.*?\/).*/g, '$1');

alert(theHostnameOfYourScript);

jsfiddle example: http://alpha.jsfiddle.net/XsJn8/

If you know the filename of your script (and if this is always the same and unique) you can use this snippet to get the hostname.

If this path is relative (and contains no host) you can get the hostname with a simple location.hostname