Setting A Site Wide Cookie With JavaScript
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.
Thank you. Its amazing how many online cookie ‘how to’ pages do not accommodate this fundamentally basic and crucial point?!