2

My objective is to get the "main" domain name of the current page in JS. By "main", I mean that all these domains should return the same result, "domain":

  • domain.com
  • domain.co.uk
  • subdomain.domain.com
  • subdomain.domain.co.uk

As you can see, splitting the query at each period and using a fixed index won't work, as the second and third URLs are of the same length, but the main domain is at different indexes.

Does the browser even recognise a part of the domain as the "main" domain? If so, is there a straight forward way to get it with JS? Are there any libraries that can help me with this?

Oscar
  • 128
  • 1
  • 6
  • `window.location.hostname.split(".")[0]`. – Wais Kamal Aug 13 '20 at 17:42
  • Does this answer your question? [Get The Current Domain Name With Javascript (Not the path, etc.)](https://stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc) – Wais Kamal Aug 13 '20 at 17:43
  • Are this urls pages you are in or strings ? – fedesc Aug 13 '20 at 17:43
  • @fedesc I am writing a chrome plug-in so I have access to all the standard web API's. – Oscar Aug 13 '20 at 17:50
  • @WaisKamal The first solution doesn't work when there's a subdomain, and the linked question doesn't really provide a way to do it either. – Oscar Aug 13 '20 at 18:01
  • You would need to explain why you need to do this to have proper answer. Because, without doing live queries and without using an external reference like the Mozilla PSL (which browsers are using, hence their solution is done that way), there is NO WAY to do what you want (just observing the string can not give information on the administrative boundaries) – Patrick Mevzek Aug 21 '20 at 17:46

1 Answers1

1

try psl libraries

// Parse domain with nested subdomains
var parsed = psl.parse('a.b.c.d.foo.example');
console.log(parsed.tld); // 'example'
console.log(parsed.sld); // 'foo'
console.log(parsed.domain); // 'foo.example'
console.log(parsed.subdomain); // 'a.b.c.d'
Patrick Mevzek
  • 10,995
  • 16
  • 38
  • 54
Mohammad Ali Rony
  • 4,695
  • 3
  • 19
  • 33