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

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

问题描述

我想从 javascript 中的 url 中提取基本域.例如,对于下面列出的网址列表,我需要获得 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
图片.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 中找到基本 url.

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天全站免登陆