269

Given that I'm on the following page:

http://www.webmail.com/pages/home.aspx

How can I retrieve the host name ("http://www.webmail.com") with JavaScript?

Syscall
  • 19,327
  • 10
  • 37
  • 52
karthik k
  • 3,751
  • 15
  • 54
  • 68
  • 5
    possible duplicate of [Get host name in JavaScript](http://stackoverflow.com/questions/1368264/get-host-name-in-javascript) – T.Todua Mar 19 '15 at 09:55
  • I simply did `console.log(window.location)`. You will see all available attributes and their values. Only the port part is something you have to worry about, see answers below (or print the info on web page with non-standard port) – Petr Újezdský Oct 21 '22 at 09:39

9 Answers9

450
// will return the host name and port
var host = window.location.host; 

or possibly

var host = window.location.protocol + "//" + window.location.host;

or if you like concatenation

var protocol = location.protocol;
var slashes = protocol.concat("//");
var host = slashes.concat(window.location.host);

// or as you probably should do
var host = location.protocol.concat("//").concat(window.location.host);

// the above is the same as origin, e.g. "https://stackoverflow.com"
var host = window.location.origin;

If you have or expect custom ports use window.location.host instead of window.location.hostname

Eric Herlitz
  • 25,354
  • 27
  • 113
  • 157
  • 3
    Maybe don't specify `http` though. Use the relative protocol. Might be more appropriate than hard-coding one. – Darth Egregious May 13 '15 at 15:32
  • Thanks for updating it Eric, but it's still not correct. You don't need to reference location.protocol at all. – Darth Egregious May 14 '15 at 14:17
  • 37
    Use window.location.host instead of hostname, or it will fail if the port is not 80. – Stefan Steiger Jun 19 '15 at 09:03
  • To use the relative protocol, as @Fuser97381 suggested (this way it will work for either http or https: `var host = '//' + window.location.hostname` – Matt Browne Aug 20 '15 at 16:06
  • BTW what is the point of using the `concat` function here rather than just using `+`? I don't see how using `concat` would have any advantage at all... – Matt Browne Aug 20 '15 at 16:07
  • 1
    @MattBrowne When working with something that shall produce a string I'd say you should always use `concat`. In example `var a = 1 + 2 + " should be 12";` vs the concat version of this `var a = "".concat(1).concat(2).concat(" should be 12");`. Using concat will save you a lot of trouble `+` is for calculation, not concatenation. – Eric Herlitz Aug 20 '15 at 19:42
  • 3
    `hostname` will give only domain and `host` will provide port also. This is great mini tool to see link anatomy http://bl.ocks.org/abernier/3070589 – Lukas Liesis Apr 11 '16 at 05:00
  • 5
    window.location.origin works well too - it includes the protocol and the port. – rothschild86 Jun 05 '17 at 15:49
  • Confusingly `window.location.protocol` already contains a colon `:`, instead of actually merely the protocol … Pretty sure the protocols are actually named without `:`, as in `HTTP` and `HTTPS`, but I guess this is JS doing JS things. – Zelphir Kaltstahl Jul 06 '23 at 09:59
113

To get the hostname: location.hostname

But your example is looking for the scheme as well, so location.origin appears to do what you want in Chrome, but gets not mention in the Mozdev docs. You can construct it with

location.protocol + '//' + location.hostname

If you want the port number as well (for when it isn't 80) then:

location.protocol + '//' + location.host
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
87

You can get the protocol, host, and port using this:

window.location.origin

Browser compatibility

Desktop

Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
(Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
30.0.1599.101 (possibly earlier) ? 21.0 (21.0) 11 ? 7 (possibly earlier, see webkit bug 46558)

Mobile

Android Edge Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
(Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
30.0.1599.101 (possibly earlier) ? 21.0 (21.0) ? ? 7 (possibly earlier, see webkit bug 46558)

All browser compatibility is from Mozilla Developer Network

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Monso
  • 1,086
  • 8
  • 9
  • 4
    I should mention IE does not support this. – Monso Aug 15 '14 at 16:13
  • Please do mention that it's a new feature and not supported by old browsers. – kabirbaidhya Mar 31 '17 at 06:35
  • @kabirbaidhya How about verbose compatibility! – Monso Apr 04 '17 at 12:14
  • Good. But what happens when the MDN guys update the browser compatibility table, which happens pretty often with newer browser releases. You might need to keep on updating this to sync with their table ;). – kabirbaidhya Apr 05 '17 at 05:38
  • Not really, this is the earliest know versions to support it not the latest and all browsers they look at already support it. This would only change if they decide to include another browser of can figure out the version numbers on some of the supported browsers which is somewhat moot since most newer ones are from their initial release. – Monso Apr 05 '17 at 12:52
12
let path = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port;
user3601578
  • 1,310
  • 1
  • 18
  • 29
7

Depending on your needs, you can use one of the window.location properties. In your question you are asking about the host, which may be retrieved using window.location.hostname (e.g. www.example.com). In your example you are showing something what is called origin, which may be retrieved using window.location.origin (e.g. http://www.example.com).

var path = window.location.origin + "/";

//result = "http://localhost:60470/"
Vadim
  • 8,701
  • 4
  • 43
  • 50
Mahmoud Salah Eldin
  • 1,739
  • 16
  • 21
7

This should work:

window.location.hostname
royhowie
  • 11,075
  • 14
  • 50
  • 67
GordyD
  • 5,063
  • 25
  • 29
6

You can try something like that:

1. Get the full URL:

     window.location

2. Get the only protocol:

    window.location.protocol

3. Get the host:

    window.location.host

4. Get the host and protocol:

    window.location.origin

5. Get pathname or directory without protocol and host:

    var url = 'http://www.example.com/somepath/path2/path3/path4';
    
    var pathname = new URL(url).pathname;
    
    alert(pathname); 
5

Keep in mind before use window and location

1.use window and location in client side render (Note:don't use in ssr)

window.location.host; 

or

var host = window.location.protocol + "//" + window.location.host;

2.server side render

if your using nuxt.js(vue) or next.js(react) refer docs

For nuxt js Framework

req.headers.host

code:

async asyncData ({ req, res }) {
        if (process.server) {
         return { host: req.headers.host }
        }

Code In router:

export function createRouter (ssrContext) {



console.log(ssrContext.req.headers.host)   
      return new Router({
        middleware: 'route',
        routes:checkRoute(ssrContext),
        mode: 'history'
      })
    }

For next.js framework

Home.getInitalProps = async(context) => {
   const { req, query, res, asPath, pathname } = context;
   if (req) {
      let host = req.headers.host // will give you localhost:3000
     }
  }

For node.js users

var os = require("os");
var hostname = os.hostname();

or

request.headers.host

For laravel users

public function yourControllerFun(Request $request) {

    $host = $request->getHttpHost();

  

    dd($host);

}

or

directly use in web.php

Request::getHost();

Note :

both csr and ssr app you manually check example ssr render

if(req.server){
host=req.host;
}
if(req.client){
host=window.location.host; 
}
Balaji
  • 9,657
  • 5
  • 47
  • 47
4

I like this one depending of purpose

window.location.href.split("/")[2] == "localhost:17000" //always domain + port

You can apply it on any url-string

var url = "http://localhost:17000/sub1/sub2/mypage.html?q=12";
url.split("/")[2] == "localhost:17000"
url.split("/")[url.split("/").length-1] == "mypage.html?q=12"

Removing protocol, domain & path from url-string (relative path)

var arr = url.split("/");
if (arr.length>3)
   "/" + arr.splice(3, arr.length).join("/") == "/sub1/sub2/mypage.html?q=12"
Gosso
  • 141
  • 6