Skip to content

Instantly share code, notes, and snippets.

@polarity
Last active December 10, 2015 03:28
Show Gist options
  • Save polarity/4375021 to your computer and use it in GitHub Desktop.
Save polarity/4375021 to your computer and use it in GitHub Desktop.
How to read and write a cookie
// page one: set cookie after successful login
setCookie("myLogin", "Username or a different String", 2);
// page two: get cookie with this variable name
var cookie = readCookie("myLogin");
// redirect if theres no cookie with this variable
if (!cookie) {
// redirect to page one
document.location = "/pageone.html";
}
/**
* Some helper functions :)
*/
/**
* Write a cookie
* @param {string} cookieName Name of the cookie
* @param {string} cookieValue Value of the cookie Variable
* @param {int} nDays How long until the cookie expires
*/
function setCookie(cookieName, cookieValue, nDays) {
var today = new Date();
var expire = new Date();
if (nDays === null || nDays === 0) {
nDays = 1;
}
expire.setTime(today.getTime() + 3600000 * 24 * nDays);
document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString();
}
/**
* Read a cookie variable
* @param {string} cookieName Name of the cookie variable
* @return {string} content of the cookie
*/
function readCookie(cookieName) {
var re = new RegExp('[; ]' + cookieName + '=([^\\s;]*)');
var sMatch = (' ' + document.cookie).match(re);
if (cookieName && sMatch) {
return unescape(sMatch[1]);
}
return '';
}​​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment