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 would try the following combinations...
"" -> fail
"" -> success, return
"" -> skipped, because already found

Examples: -> -> -> ->

Try it out on JSFiddle


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;

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