Javascript - Get Domain Name Excluding Subdomain

published on June 13th, 2014 · more from the blog →

Recently I needed some javascript to get the Domain name excluding any subdomains. Whilst it's very difficult to work this out using a regular expression or similar, as you have to account for many diffeent TLD's, what I have come up with is a script that can get the domain of the current page (which was my use case).

How does it work?
It loops through the parts of a full hostname and tries to set a cookie on that domain, it will set a cookie at the highest level possible.
For example www.rossscrivener.co.uk would try the following combinations...
".co.uk" -> fail
"rossscrivener.co.uk" -> success, return
"www.rossscrivener.co.uk" -> skipped, because already found

Examples:
google.co.uk -> google.co.uk
www.google.co.uk -> google.co.uk
whatever.google.com -> google.com
whatever.whatever.google.co.uk/hello.html -> google.co.uk

Try it out on JSFiddle

Code:

var domain = (function(){
   var i=0,domain=document.domain,p=domain.split('.'),s='_gd'+(new Date()).getTime();
   while(i<(p.length-1) && document.cookie.indexOf(s+'='+s)==-1){
      domain = p.slice(-1-(++i)).join('.');
      document.cookie = s+"="+s+";domain="+domain+";";
   }
   document.cookie = s+"=;expires=Thu, 01 Jan 1970 00:00:01 GMT;domain="+domain+";";
   return domain;
})();

Caveats:
- Obviously this technique will only work if you can run the javascript on the domain of the page you want the hostname of.
- Cookies must be enabled on the client browser.