Reputation: 2599
Is it possible to store a JS cookie for the current domain including subdomains.
e.g.:
document.cookie = "key=value; expires=Tue, 16 Apr 2019 11:31:56 GMT; path=/;secure"
sets a cookie for the current domain but does not add a dot to the domain name.
I know that it is possible to specify the domain via domain=.example.com
but I do not want to hardcode the domain name.
I tried something like this but it did not work out:
document.cookie = "key=value; expires=Tue, 16 Apr 2019 11:31:56 GMT; path=/;secure;domain=."
Update:
I know you can get the current domain with window.location.hostname
but is there a solution where i do not need to get the domain name programmatically
UPDATE 2:
like described here: What does the dot prefix in the cookie domain mean?
The leading dot means that the cookie is valid for subdomains as well; nevertheless recent HTTP specifications (RFC 6265) changed this rule so modern browsers should not care about the leading dot. The dot may be needed by old browser implementing the deprecated RFC 2109.
This means that it does not make a difference if you use a dot before the domain name in modern browsers. That said, you can leave the domain section of the JS cookie blank and it is set to the current domain (which also matches subdomains)
Upvotes: 4
Views: 14894
Reputation: 2599
Possible solution:
var domainName = window.location.hostname;
document.cookie = "key=value; expires=Tue, 16 Apr 2019 11:31:56 GMT; path=/; secure; domain=." + domainName;
Upvotes: 5