Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Figuring out Host's Top Domain with Javascript

Tags:

javascript

Is there a way to figure out what the top domain for the hostname of the current page is? The problem I have is that the script could be on .com domain, or in an international domain like .co.uk

So for: jobs.telegraph.co.uk - top domain is:telegraph.co.uk jobs.nytimes.com - top domain is nytimes.com

The problem is that location.hostname , and the document.domain give the entire domain.

One route is to have a list of all TLDs (too much to carry around) and parse based on that. Another route was if 2 characters after last ".", than internationaltion - hence last two are the TLD, but that does not hold true for all international domains.

like image 722
timeitquery Avatar asked Feb 27 '26 10:02

timeitquery


1 Answers

The Top domain is the first one you can set cookies in. Browsers will block cookies for all TLDs by default. Provided that the previous sentence is true you can exploit it to get the Top Domain for the current page.

function get_top_domain(){
  var i,h,
    weird_cookie='_weird_get_top_level_domain=cookie',
    hostname = document.location.hostname.split('.');
  for(i=hostname.length-1; i>=0; i--) {
    h = hostname.slice(i).join('.');
    document.cookie = weird_cookie + ';domain=' + h + ';';
    if(document.cookie.indexOf(weird_cookie)>-1){
      document.cookie = weird_cookie.split('=')[0] + '=;domain=' + h + ';expires=Thu, 01 Jan 1970 00:00:01 GMT;';
      return h;
    }
  }
}
like image 89
Eduardo Avatar answered Mar 02 '26 00:03

Eduardo