Jeremy Harris Jeremy Harris - 1 year ago 105
Javascript Question

Javascript Get Hostname of File Host

Although this question is similar, it is not what I am looking for.

Let's say on I include a script from

<script type="text/javascript" src="">

When script.js runs, I need to get the name of HostB (let's assume it can change). If I use:

var hostName = window.location.hostname;

It will return rather than obviously because that is where the the
object is scoped.

How can I get the name of HostB from within the script? Do I have to locate the
element in the DOM and parse the
attribute or is there a better way?


Yes, it is on my server, but may be on other servers as well. I am developing a javascript plugin and am trying to make absolute paths so it doesn't try to reference files on the server including the plugin.

Answer Source

I am loading the script with RequireJS which looks something like this:

<script data-main="" src="" type="text/javascript"></script>

I figured out, with help from @adeneo that I can do something like this:


Which returns:

And I can parse it for the hostname.

var url = $('script[data-main*="/main.js"]').attr('data-main');
parser = document.createElement('a');
parser.href = url;
host = parser.hostname;

Thanks for the suggestions and nudge in the right direction!


Turns out their is an easier way for anyone using RequireJS (who finds this question in search) and needs to be able to load absolute URL's with the script host:

var myCssPath = require.toUrl('css/mystyles.css');

That builds an absolute path using the hostname of the server running!