如何从JavaScript中的URL获取基本域 [英] How to get base domain from the URL in JavaScript

查看:61
本文介绍了如何从JavaScript中的URL获取基本域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从javascript中的网址中提取基本域. 例如,对于下面列出的网址列表,我需要获取 google.com (或视情况而定为 google.co.in ).

I would like to extract the base domain from the url in javascript. For example for the list of urls listed below I need to get google.com (or google.co.in as the case may be) as the result.

www.google.com
www.google.co.in
www.images.google.com
www.images.google.co.in
google.com
google.co.in
images.google.com
images.google.co.in

www.google.com
www.google.co.in
www.images.google.com
www.images.google.co.in
google.com
google.co.in
images.google.com
images.google.co.in

任何人都知道如何做.我猜没有直接的方法可以在javascript中找到基本网址.

Any one got some idea on how to do it. There is no direct method to find the base url in javascript i guess.

推荐答案

仅当您要获取顶级主机名的URL时,此方法才有效.

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

此函数可确保您获得顶级主机名,因为这是浏览器允许您设置Cookie的最小主机.我们测试是否可以为给定前缀设置Cookie,如果返回,则返回该值,否则尝试下一个加上前缀,直到找到有效的那个.

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.

如果将浏览器配置为禁止cookie,或者可能使用受限制的主机名(例如localhost

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,
    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){
      // 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;
    }
  }
}

这篇关于如何从JavaScript中的URL获取基本域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆