How to get base domain from the URL in JavaScript

This one works only if you are at the url you want to get the Top Level Hostname.

This function guarantees you get the top-level hostname because that’s the smallest one browsers will let you set cookies in. We test if for a given prefix we are able to set cookies, if so we return that otherwise we try the next prefix until we find the one that works.

Will fail if the browser is configured to disallow cookies, or possibly in restricted hostnames such as localhost

function get_top_domain(){
  var i,h,
    hostname = document.location.hostname.split('.');
  for(i=hostname.length-1; i>=0; i--) {
    h = hostname.slice(i).join('.');
    document.cookie = weird_cookie + ';domain=.' + h + ';';
      // We were able to store a cookie! This must be it
      document.cookie = weird_cookie.split('=')[0] + '=;domain=.' + h + ';expires=Thu, 01 Jan 1970 00:00:01 GMT;';
      return h;

Leave a Comment