JavaScript Cookie在子域上不起作用

时间:2019-05-24 13:19:29

标签: javascript cookies

我有一个cookie授权横幅,上面有一个标有“知道了!”的按钮。消除它。我通过设置Cookie来做到这一点。

要设置Cookie,请在<head>中放入它:

<script>

    function setCookie(cname, cvalue, exdays)
        {
            var d = new Date();
            d.setTime(d.getTime() + (exdays*24*60*60*1000));
            var expires = "expires="+ d.toUTCString();
            var domain = ".brokenhearts.ml";
            var security = "secure";
            var location = "/";
            document.cookie = cname + "=" + cvalue + ";" + expires + ";" + location + ";" + domain + ";" + security;
        }

</script>

并且我将其设置为在单击按钮时执行:

var privacyValue = "yes";
setCookie("privacy", privacyValue, 365);

问题是,当我在Chrome中检查Cookie时,它显示出如下内容:

{{3}}

如您所见,该cookie仅针对www.brokenhearts.ml设置,而不针对其子域设置。我希望为所有子域设置Cookie。

我尝试将cookie的域设置为“ brokenhearts.ml”,但仍仅对www.brokenhearts.ml设置。

1 个答案:

答案 0 :(得分:1)

设置Cookie时,您的域必须采用.domain.com的格式–点和根域以及path=/总是。

如果您未设置path=/,则自动路径将被保存为cookie的保存位置,因此将无法在任何子域中访问它。

//variables
var LastReportGenerated="Jul 11 2013",
baseDomain = '.cssjunction.com',
expireAfter = new Date();

//setting up  cookie expire date after a week
expireAfter.setDate(expireAfter.getDate() + 7);

//now setup cookie
document.cookie="Report={'ReportName':'MainReport', 'lastGenerated':" + LastReportGenerated + "}; domain=" + baseDomain + "; expires=" + expireAfter + "; path=/";

来源:

How to set cookies to share across all subdomains using JavaScript