问题描述
我有一个Cookie授权标语,上面有一个标有知道了!的按钮,可以将其关闭。我通过设置cookie来做到这一点。
I have a cookie authorization banner, with a button labeled 'Got it!' that dismisses it. I do that by setting a cookie.
要设置cookie,请在我的< head>
:
To set a cookie, I have this in my <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>
我将其设置为在单击按钮时执行:
and I've set this to be executed when the button is clicked:
var privacyValue = "yes";
setCookie("privacy", privacyValue, 365);
问题是,当我在Chrome中检查Cookie时,显示的内容如下:
The problem is, when I check for the cookie in Chrome, it shows me something like this:
如您所见,Cookie仅针对www.brokenhearts.ml,而不是其子域。我希望对所有子域都设置cookie。
As you can see, the cookie is getting set only for www.brokenhearts.ml and not for its sub-domains. I want the cookie to be set for all sub-domains.
我尝试将域的cookie设置为 brokenhearts.ml,但仍仅为www设置.brokenhearts.ml。
I tried setting the cookie with the domain as "brokenhearts.ml" and it still gets set only for www.brokenhearts.ml.
推荐答案
设置Cookie时,您的域的格式必须为。 domain.com
–点和根域以及 path = /
始终。
When setting up the cookie, your domain must be in format of .domain.com
– dot and root domain and path=/
, always.
如果您未设置 path = /
,则自动路径将保存为Cookie所在的位置保存-因此将无法在任何子域中访问。
If you don't set path=/
, auto path will be saved as from where the cookies is being saved - hence it wont be accessible across any subdomain.
//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=/";
来源:
这篇关于JavaScript Cookie在子域上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!