Creating JavaScript cookies in a domain and reading it in subdomains

The following is a JavaScript cookie that has been written on a user's computer for 12 months.

After we set a cookie in our main domain, for example example.com , if a user visits a subobject, for example test.example.com , we need to continue identifying user activity through our β€œtest” subdomain.

But with the current code, once they leave www.example.com and visit test.example.com , they are no longer marked as "HelloWorld".

Can someone help with my code so cookies can be read through 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> 
+84
javascript cookies
Apr 15 '11 at 1:14
source share
4 answers

Just set the domain and path attributes in your cookie, for example:

 <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> 
+178
Apr 15 '11 at 1:17
source share

Do you want to:

 document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate; 

In accordance with RFC 2109 , in order for the cookie to be accessible for all subdomains, you must supply . in front of your domain.

Setting path = / will have cookies within the entire specified domain (aka .example.com ).

+25
Apr 15 '11 at 1:17
source share

Here is a working example:

 document.cookie = "testCookie=cookieval; domain=." + location.hostname.split('.').reverse()[1] + "." + location.hostname.split('.').reverse()[0] + "; path=/" 

This is a general solution that takes the root domain from a location object and sets a cookie. This is because you do not know how many subdomains you have, if any.

+3
Feb 12 '16 at 16:42 on
source share

You can also use the MDN JavaScript Cookie Framework and follow these steps:

 docCookies.setItem('HelloWorld', 'HelloWorld', myDate, '/', 'example.com'); 
+1
Oct 28 '16 at 5:11
source share



All Articles