Setting A Site Wide Cookie With JavaScript

February 26th, 2013 - Posted by Steve Marks to Javascript / jQuery, Web Development.

In JavaScript it’s possible to set a cookie in order to remember a users preference, or to track information about a user’s visit. If, like me, you looked on the W3Schools website to find out how to set cookies you’ll see that they recommend the following JavaScript code:

function setCookie(c_name, value, exdays)
{
	var exdate = new Date();
	exdate.setDate( exdate.getDate() + exdays );
	var c_value = escape( value ) + ( ( exdays == null ) ? "" : "; expires=" + exdate.toUTCString() );
	document.cookie = c_name + "=" + c_value;
}

This definitely works and sets the cookie successfully, but with one caveat; It only sets a cookie for the current page, meaning it won’t be available on all the other pages on a site.

The Solution

So how do we make the cookie accessible site wide? Well, we can achieve this by making a slight adjustment to the code above like so:

function setCookie(c_name, value, exdays)
{
	var exdate = new Date();
	exdate.setDate( exdate.getDate() + exdays );
	var c_value = escape( value ) + ( ( exdays == null ) ? "" : "; expires=" + exdate.toUTCString() );
	document.cookie = c_name + "=" + c_value + "; path=/";
}

By adding the ‘path’ parameter to the cookie contents we can specify in which directories the cookie will be available from. In this case we can set it to ‘/’ (the root directory of the site) and thus make it site wide.

This entry was posted on Tuesday, February 26th, 2013 at 2:08 pm by +Steve Marks and is filed under Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (1)
  1. DH says:

    Thank you. Its amazing how many online cookie ‘how to’ pages do not accommodate this fundamentally basic and crucial point?!