0

I'am looking for a way to get the top-level domain from a website. For ex.

  • From www.google.com => return google.com
  • From subsite.site.com => return site.com
  • From subsite.site.co.uk => return site.co.uk

As a basis, I can use document.domain or location.hostname but its doesn't get the top-level domain. I need it in order to build a cookie that would be stable on the whole domain.

The best we found today:

      var t = document.domain.split(".");
      if (t.length > 2) {
        domain_name = t.slice(1).join(".");
      }

i.a. if a domain has more than 2 parts, remove the first part. It seems quite OK but I am not that confident.

Is there a better way?

Rolintocour
  • 2,934
  • 4
  • 32
  • 63

1 Answers1

0

window.location.origin
The origin read-only property of the Location interface is a USVString containing the Unicode serialization of the origin of the represented URL.
location.host
Is a USVString containing the host, that is the hostname, a ':', and the port of the URL. location.hostname
Is a USVString containing the domain of the URL.

read : Location - Web APIs

console.log(window.location.origin);
console.log( window.location.host );
console.log( window.location.hostname );
Hanna Rose
  • 412
  • 2
  • 9