location.host vs location.hostname and cross-browser compatibility? location.host vs location.hostname and cross-browser compatibility? javascript javascript

location.host vs location.hostname and cross-browser compatibility?


interactive link anatomy

As a little memo: the interactive link anatomy

--

In short (assuming a location of http://example.org:8888/foo/bar#bang):

  • hostname gives you example.org
  • host gives you example.org:8888


host just includes the port number if there is one specified. If there is no port number specifically in the URL, then it returns the same as hostname. You pick whether you care to match the port number or not. See https://developer.mozilla.org/en/window.location for more info.

I would assume you want hostname to just get the site name.


If you are insisting to use the window.location.originYou can put this in top of your code before reading the origin

if (!window.location.origin) {  window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');}

Solution

PS: For the record, it was actually the original question. It was already edited :)