JavaScript By Example

Cookies: 3. Domain Level Cookies

Web sites often have a www. sub-domain that points to the same content as the main domain. With session cookies our visitor has either accessed our site with the www. or they have accessed it without and so the fact that a cookie created for is not accessible from isn't going to matter. With first party cookies a visitor may very easily access our site the first time as and the second time as and so we want to create a cookie that will be accessible from both.

To make a cookie accessible from the entire domain including any sub-domains we just add a domain parameter when setting the cookie as demonstrated in this example. You should of course substitute your own domain name for (as is a domain name specifically reserved for use in examples where it represents whatever domain name you are really using.

writeCookie = function(cname, cvalue, days) {
var dt, expires;
dt = new Date();
expires = "; expires="+dt.toGMTString();
document.cookie = cname+"="+cvalue+expires+';';