How to get the host URL using JavaScript from the current page

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

// 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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

let path = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port;

Solution 5 - Javascript

This should work:

window.location.hostname

Solution 6 - Javascript

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/"

Solution 7 - Javascript

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); 

Solution 8 - Javascript

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; 
}

Solution 9 - Javascript

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionkarthik kView Question on Stackoverflow
Solution 1 - JavascriptEric HerlitzView Answer on Stackoverflow
Solution 2 - JavascriptQuentinView Answer on Stackoverflow
Solution 3 - JavascriptMonsoView Answer on Stackoverflow
Solution 4 - Javascriptuser3601578View Answer on Stackoverflow
Solution 5 - JavascriptGordyDView Answer on Stackoverflow
Solution 6 - JavascriptMahmoud Salah EldinView Answer on Stackoverflow
Solution 7 - JavascriptZubairView Answer on Stackoverflow
Solution 8 - JavascriptßãlãjîView Answer on Stackoverflow
Solution 9 - JavascriptGossoView Answer on Stackoverflow