从没有子域等的URL解析主机

And*_*ini 1 javascript url google-chrome-extension

我正在研究从中读取域的chrome扩展window.location.hostname.现在,为了使此扩展能够正常工作,我需要能够将子域和其他URL变体分离到同一主机.例:

我需要以下所有url:s

www.google.com
accounts.google.com
photos.google.se
example.google.co.uk
https://google.com
Run Code Online (Sandbox Code Playgroud)

所有这些都需要解决,在这种情况下,"谷歌",以一种可靠的方式,并适用于任何网站有时古怪的子域配置.

这是我目前的方法,有点简化:

var url = window.location.hostname.split(".") //returns an array of strings
for(i=0;i<url.length;i++){
if(url[i].match(domainregex) //regex for identifying domains ".com",".se",".co.uk" etc
return url[i-1]  //usually what I'm after is directly before the domain, thus i-1
}
Run Code Online (Sandbox Code Playgroud)

这种方法很麻烦,有时候证明不可靠......有没有更直接的方法呢?

wOx*_*xOm 5

剥离顶级域名部分并获得主域名部分的更可靠的解决方案是使用Firefox和Chrome以及其他浏览器使用的公共后缀列表.

如果您不想编写自己的列表数据,可以使用列表数据的几个js解析器.