Jeremy Harris Jeremy Harris - 3 months ago 18
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 HostA.com I include a script from HostB.com:

<script type="text/javascript" src="http://www.hostb.com/script.js">


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 HostA.com rather than HostB.com obviously because that is where the the
window
object is scoped.

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

EDIT



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

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

<script data-main="http://hostb.com/js/app/main.js" src="http://hostb.com/js/vendor/require.js" type="text/javascript"></script>

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

$('script[data-main*="/js/app/main.js"]').attr('data-main')

Which returns:

http://hostb.com/js/app/main.js

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!

BREAKING NEWS

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!

Comments