js创建cookie时获取一级域名设置domain解决跨域问题

解决子域和主域的cookie问题:
function GetCookieDomain() {
 var host = location.hostname;
 var ip = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
 if (ip.test(host) === true || host === 'localhost') return host;
 var regex = /([^]*).*/;
 var match = host.match(regex);
 if (typeof match !== "undefined" && null !== match) host = match[1];
 if (typeof host !== "undefined" && null !== host) {
  var strAry = host.split(".");
  if (strAry.length > 1) {
   host = strAry[strAry.length - 2] + "." + strAry[strAry.length - 1];
  }
 }
 return '.' + host;
}

支持本地环境(仅判断localhost)、host为ip地址、中文域名、常规域名。如下图所示:
《js创建cookie时获取一级域名设置domain解决跨域问题》
调用很简单,写了个示例:

document.cookie = cname + "=" + cvalue + "; expires=" + expires + "; domain=" + GetCookieDomain() + "; path=/";
    原文作者:活在当下_未来可期
    原文地址: https://blog.csdn.net/Paranoid99/article/details/101015172
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞