Web tricks - Some hot cookies?
Cookies are a way to store information on the user's computer. We can use them for a lot of different things: store the language, the graphical theme, login information (beware of security issues though), etc...
Here are a set of functions to manipulate those cookies through JavaScript.
Get
/** * Function to get a JavaScript cookie. * * @see http://www.w3schools.com/js/js_cookies.asp * * @param cName Name of the cookie to get. * @returns the value of the cookie, null if not found. */ function getCookie(cName) { var i, n, name, value, cookies = document.cookie.split(";"); for (i = 0, n = cookies.length ; i < n ; i++) { name = cookies[i].substr(0, cookies[i].indexOf("=")); name = name.replace(/^\s+|\s+$/g, ""); if (name == cName) { value = cookies[i].substr(cookies[i].indexOf("=") + 1); return decodeURIComponent(value); } } return null; }
Set
/** * Function to set a JavaScript cookie. * * @see http://www.w3schools.com/js/js_cookies.asp * * @param name Name of the cookie to set. * @param value Value of the cookie. * @param exDays (Optional) Days before expiration of the cookie. * @param domain (Optional) Domain on which the cookie is available. * @param path (Optional) Path on the server in which the cookie is available. * @param secure (Optional) Whether the cookie should be transmitted over a * secure HTTPS. * @param httponly (Optional) Whether the cookie should be accessible through * HTTP only (meaning it won't be accessible to client scripts). */ function setCookie(name, value, exDays, domain, path, secure, httponly) { // Name must be set if (name == null) return false; var exDate = new Date(); exDate.setDate(exDate.getDate() + exDays); var value = encodeURIComponent(value); var expires_string = ((exDays == null) ? "" : "; expires=" + exDate.toUTCString()); var domain_string = ((domain == null) ? "" : "; domain=" + domain); var path_string = ((path == null) ? "" : "; path=" + path); var secure_string = ((secure == null || !secure) ? "" : "; Secure"); var httponly_string = ((secure == null || !secure) ? "" : "; Httponly"); document.cookie = name + "=" + value + expires_string + domain_string + path_string + secure_string + httponly_string; return true; }
Unset
/** * Function to unset a JavaScript cookie. * * @param name Name of the cookie to unset. */ function unsetCookie(name) { return setCookie(name, "", -1); }
More information
- Dad ! Dad ! How do you cook cookies?
- ... Ask Wiki.
To get the cookies out of the oven: Fire Cookie.