486

I plan on buying two domain names for the same site. Depending on which domain is used I plan on providing slightly different data on the page. Is there a way for me to detect the actual domain name that the page is loading from so that I know what to change my content to?

I've looked around for stuff like this but most of it doesn't work the way I want it to.

For instance when using

document.write(document.location)

on JSFiddle it returns

http://fiddle.jshell.net/_display/

i.e. the actual path or whatever that is.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
Freesnöw
  • 30,619
  • 30
  • 89
  • 138
  • 1
    I'm not sure if I understand exactly what you want to do, but you should probably take a look into [MDN](https://developer.mozilla.org/en/DOM/window.location) in regards to this – MilkyWayJoe Jul 09 '12 at 19:39
  • 2
    A bit of topic, but you could also consider having subdomains rather then two separate domain names. Something like `premium.random.com` and `free.random.com` – T.Chmelevskij Jan 10 '17 at 08:29

19 Answers19

753

How about:

window.location.hostname

The location object actually has a number of attributes referring to different parts of the URL

Gareth
  • 133,157
  • 36
  • 148
  • 157
  • 83
    and `window.location.hostname` if you don't want to get the `port` (like `http://localhost:3000/`, `window.location.host = 'localhost:3000'` and `window.location.hostname = 'localhost'` – Guilherme Feb 16 '15 at 14:32
  • 9
    The answer is wrong because port does not belong to domain. And `window.location.host` will sometimes give the port back. – Andrej Mar 14 '16 at 14:54
  • 7
    This also returns the server name ('www.amazingjokes.com', instead of just '.amazingjokes.com') – patrick May 18 '16 at 13:22
  • In case you have forwarding DNS you might need this one - window.location.ancestorOrigins – Kirill Husiatyn Jun 04 '20 at 14:28
  • a simple one-liner to copy paste in your browser console to inspect the `window.location` object is `((l)=>Object.keys(l).reduce((m,p)=>{if(typeof l[p]==="string"){m[p]=l[p];}return m;},{}))(location)`, to inspect the result parsed `URL` instead just `new URL(window.location)` – kuus May 26 '22 at 10:18
714

Let's suppose you have this url path:

http://localhost:4200/landing?query=1#2

So, you can serve yourself by the location values, as follow:

window.location.hash: "#2"
​
window.location.host: "localhost:4200"
​
window.location.hostname: "localhost"
​
window.location.href: "http://localhost:4200/landing?query=1#2"
​
window.location.origin: "http://localhost:4200"
​
window.location.pathname: "/landing"
​
window.location.port: "4200"
​
window.location.protocol: "http:"

window.location.search: "?query=1"

Now we can conclude you're looking for:

window.location.hostname
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
Sunil Shakya
  • 8,097
  • 2
  • 17
  • 20
27
function getDomain(url, subdomain) {
    subdomain = subdomain || false;

    url = url.replace(/(https?:\/\/)?(www.)?/i, '');

    if (!subdomain) {
        url = url.split('.');

        url = url.slice(url.length - 2).join('.');
    }

    if (url.indexOf('/') !== -1) {
        return url.split('/')[0];
    }

    return url;
}

Examples

Previous version was getting full domain (including subdomain). Now it determines the right domain depending on preference. So that when a 2nd argument is provided as true it will include the subdomain, otherwise it returns only the 'main domain'

adelindev
  • 538
  • 4
  • 10
  • 1
    This should be the answer, it works even in `localhost/test.php` and that the correct answer `localhost`. – Mohammed AlBanna Jul 12 '16 at 14:07
  • 1
    It's also the best answer because it works with any URL you pass in, not just the current window.location – sohtimsso1970 Mar 10 '17 at 15:17
  • 3
    If you do this to `google.co.uk` for you'll get 'co.uk' back, which is not correct... – James Douglas Oct 26 '18 at 09:17
  • Yes. That's a tricky business. Even trickier if you got subdomains too (like: test.google.co.uk). If you want to use this raw version some serious adjustments are needed (maybe even adding a special list for those tlds). – adelindev Nov 08 '18 at 10:27
24

If you are not interested in the host name (for example www.beta.example.com) but in the domain name (for example example.com), this works for valid host names:

function getDomainName(hostName)
{
    return hostName.substring(hostName.lastIndexOf(".", hostName.lastIndexOf(".") - 1) + 1);
}
cprcrack
  • 17,118
  • 7
  • 88
  • 91
  • 18
    Incorrect, this will break on nearly all international TLDs. – tbranyen Sep 19 '14 at 02:30
  • 4
    @tbranyen can you explain what are you referring to? The only case I can think about are subdomains like `amazon.co.uk`. But definitely not "nearly all international TLDs". In fact it works with 100% of the [country codes found in the Wikipedia](http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains) – cprcrack Sep 21 '14 at 00:53
  • 1
    cprcrack for some reason I thought more international (to america) tlds contained multiple dots. Thanks for correcting! – tbranyen Sep 21 '14 at 15:54
  • 1
    A number of countries work similarly to the UK: they have fixed second level domains and you can only register domains at the third level. A list of those countries is [on Wikipedia](https://en.wikipedia.org/wiki/Second-level_domain#Country-code_second-level_domains). – Gareth Jun 08 '20 at 12:11
  • @mhombach thanks for your downvote and for your "comment". However as mentioned in my "answer", the solution only works for *valid hostnames*, referring to the value returned from `window.location.hostname`. `http://www.google.com?ref=http://www.yahoo.com` is not a hostname so the function is not expected to work in that case. – cprcrack Mar 04 '22 at 12:35
  • Not mentioning "co.uk" case above, but the question mentions some url like "http://fiddle.jshell.net/_display/", and specifically "Is there a way for me to detect the actual domain name that the page is loading from[...]", so imho we are not talking about "how to etract the TLD from a validated hostname" but from something that is any valid url/domain. I understand that technically our solution is only partly wrong ("co.uk") but considering that reasing devs will likely use your codesnippet in production and so will have massive security flaws, I recommended not using it. No offense intended. – mhombach Mar 05 '22 at 17:39
16

window.location.hostname is a good start. But it includes sub-domains, which you probably want to remove. E.g. if the hostname is www.example.com, you probably want just the example.com bit.

There are, as ever, corner cases that make this fiddly, e.g. bbc.co.uk. The following regex works well for me:

let hostname = window.location.hostname;
// remove any subdomains, e.g. www.example.com -> example.com
let domain = hostname.match(/^(?:.*?\.)?([a-zA-Z0-9\-_]{3,}\.(?:\w{2,8}|\w{2,4}\.\w{2,4}))$/)[1];
console.log("domain: ", domain);
Daniel Winterstein
  • 2,418
  • 1
  • 29
  • 41
13

If you wish a full domain origin, you can use this:

document.location.origin

And if you wish to get only the domain, use can you just this:

document.location.hostname

But you have other options, take a look at the properties in:

document.location
Ricardo França
  • 2,923
  • 2
  • 18
  • 18
12

Since this question asks for domain name, not host name, a correct answer should be

window.location.hostname.split('.').slice(-2).join('.')

This works for host names like www.example.com too.

Ethan
  • 18,584
  • 15
  • 51
  • 72
12

You can get it from location object in Javascript easily:

For example URL of this page is:

http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc

Then we can get the exact domain with following properties of location object:

location.host = "www.stackoverflow.com"
location.protocol= "http:"

you can make the full domain with:

location.protocol + "//" + location.host

Which in this example returns http://www.stackoverflow.com

I addition of this we can get full URL and also the path with other properties of location object:

location.href= "http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"    
location.pathname= "questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"
Iman Sedighi
  • 7,624
  • 4
  • 48
  • 55
9

If you are only interested in the domain name and want to ignore the subdomain then you need to parse it out of host and hostname.

The following code does this:

var firstDot = window.location.hostname.indexOf('.');
var tld = ".net";
var isSubdomain = firstDot < window.location.hostname.indexOf(tld);
var domain;

if (isSubdomain) {
    domain = window.location.hostname.substring(firstDot == -1 ? 0 : firstDot + 1);
}
else {
  domain = window.location.hostname;
}

http://jsfiddle.net/5U366/4/

dmck
  • 7,801
  • 7
  • 43
  • 79
7

Use

document.write(document.location.hostname)​

window.location has a bunch of properties. See here for a list of them.

Dancrumb
  • 26,597
  • 10
  • 74
  • 130
7

I figure it ought to be as simple as this:

url.split("/")[2]

A R
  • 1,412
  • 2
  • 14
  • 29
6

If you want to get domain name in JavaScript, just use the following code:

var domain_name = document.location.hostname;
alert(domain_name);

If you need to web page URL path so you can access web URL path use this example:

var url = document.URL;
alert(url);
Flexo
  • 87,323
  • 22
  • 191
  • 272
ujjal
  • 225
  • 4
  • 8
4

What about this function?

window.location.hostname.match(/\w*\.\w*$/gi)[0]

This will match only the domain name regardless if its a subdomain or a main domain

unixdebian11
  • 121
  • 1
  • 7
  • 3
    I like this answer. But you should be aware that if using it for security-related purposes.. it can be bypassed. I.e. if you want to ensure you are on example.com, then hacker-example.com would also equal 'example.com'. window.location.hostname.match(/[a-zA-Z0-9-]*\.[a-zA-Z0-9-]*$/)[0] works. – hiburn8 Dec 16 '19 at 13:20
  • 1
    This doesn't work properly. if you run it on `www.bbc.co.uk` you will get `co.uk`. – nickpapoutsis Sep 26 '21 at 17:35
2

for my case the best match is window.location.origin

Pavel Poberezhnyi
  • 733
  • 13
  • 28
2

Combining a few answers from the above, the following works really well for me for destroying Cookies:

  /**
   * Utility method to obtain the domain URI:
   */
  fetchDomainURI() {
    if (window.location.port.length > 0) {
      return window.location.hostname;
    }
    return `.${window.location.hostname.match(/\w*\.\w*$/gi)[0]}`;
  }

Works for IP addresses with ports, e.g., 0.0.0.0:8000 etc, as well as complex domains like app.staging.example.com returning .example.com => allows for cross-domain Cookie setting and destroying.

Micheal J. Roberts
  • 3,735
  • 4
  • 37
  • 76
1

I'm new to JavaScript, but cant you just use: document.domain ?

Example:

<p id="ourdomain"></p>

<script>
var domainstring = document.domain;
document.getElementById("ourdomain").innerHTML = (domainstring);
</script>

Output:

domain.com

or

www.domain.com

Depending on what you use on your website.

1

Even if the question is about the domain name, the accepted solution includes the subdomain (eg. you get blog.example.com calling location.hostname). For future reference I suggest a one-liner to extract only the domain (eg. https://blog.example.com/index.html -> example.com) as Micheal.

location.hostname.split('.').filter(( _, i) => i < 2).join('.')

Beware! It can break when the TLD is composed of two parts (eg. .co.uk). If that's your case change 2 with 3 in the code above.

Luca
  • 21
  • 2
  • 2
1

you can use this to do away with the port number.

 var hostname = window.location.host;
 var urlWithoutPort = `https://${hostname}`;
 console.log(urlWithoutPort);
0

https://publicsuffix.org/list/

(https://github.com/publicsuffix/list/blob/master/public_suffix_list.dat)

is needed to correctly parse out all domains without suffixes, working with dots as in the answers above will never completely be correct. Feel free to run the above codes samples against the public suffixes dat file to realize this.

You can roll your own code based on this or use a package like https://www.npmjs.com/package/tldts

getDomainWithoutSuffix('google.com');        // returns `google`
getDomainWithoutSuffix('fr.google.com');     // returns `google`
getDomainWithoutSuffix('fr.google.google');  // returns `google`
getDomainWithoutSuffix('foo.google.co.uk');  // returns `google`
getDomainWithoutSuffix('t.co');              // returns `t`
getDomainWithoutSuffix('fr.t.co');           // returns `t`
getDomainWithoutSuffix('https://user:password@example.co.uk:8080/some/path?and&query#hash'); // returns `example`
edelwater
  • 2,650
  • 8
  • 39
  • 67