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
, shou
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
).
You can also use the MDN JavaScript Cookie Framework and do:
docCookies.setItem('HelloWorld', 'HelloWorld', myDate, '/', 'example.com');
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>
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.