解决子域和主域的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地址、中文域名、常规域名。如下图所示:

调用很简单,写了个示例:
document.cookie = cname + "=" + cvalue + "; expires=" + expires + "; domain=" + GetCookieDomain() + "; path=/";
本文介绍了一个用于解决子域和主域间Cookie同步问题的JavaScript函数GetCookieDomain()。该函数能有效处理本地环境、IP地址、中文域名及常规域名,确保Cookie在不同子域间的正确设置。
5469

被折叠的 条评论
为什么被折叠?



