Reputation: 3501
Below is a JavaScript cookie that is written on the user's computer for 12 months.
After we set the cookie on our main domain such as example.com
, should the user visit a subdomain like test.example.com
, we need to continue to identify the activity of the user across our "test" subdomain.
But with the current code, as soon as they leave www.example.com
and visit test.example.com
, they are no longer flagged as "HelloWorld".
Would anyone be able to help with my code to allow the cookie to be read across subdomains?
<script type="text/javascript">
var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate;
</script>
Upvotes: 135
Views: 317498
Reputation: 2146
For Browser Extensions, You can also use the Cookies API and do:
browser.cookies.set({
url: 'example.com',
name: 'HelloWorld',
value: 'HelloWorld',
expirationDate: myDate
}
MDN Set()
Method Documentation
Upvotes: 2
Reputation: 171
Here is a working example :
document.cookie = "testCookie=cookieval; domain=." +
location.hostname.split('.').reverse()[1] + "." +
location.hostname.split('.').reverse()[0] + "; path=/"
This is a generic solution that takes the root domain from the location object and sets the cookie. The reversing is because you don't know how many subdomains you have if any.
Upvotes: 10
Reputation: 64137
You want:
document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;
As per the RFC 2109, to have a cookie available to all subdomains, you must put a .
in front of your domain.
Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com
).
Upvotes: 45
Reputation: 54806
Just set the domain
and path
attributes on your cookie, like:
<script type="text/javascript">
var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate
+ ";domain=.example.com;path=/";
</script>
Upvotes: 256