Dec 14 2019, 9:00pm
A practical excerpt from JavaScript - Cookies to manage HTTP cookie: creation / update, reading and deleting / expiring it. I also think that it'd best to wrap these as a CookieMan object below.
In short, this is a getter / setter to one only cookie named as COOKIEMAN. cookie value (content) must be a valid JSON object (instead of a JSON string).
function CookieMan(){ //private var COOKIENAME = 'COOKIEMAN', SC_SP = '; ', EQ = '=', YESTERDAY = -24 * 60 * 60 * 1000; //public this.val = function(){ if(arguments.length === 0){//is a getter var ret = false; if(document.cookie.length > 0){ var parts = document.cookie.split(SC_SP); for(var i = 0; i < parts.length; i++){ var keyVal = parts[i].split(EQ); if(keyVal[0].trim() === COOKIENAME && keyVal[1].length > 0){ ret = JSON.parse(decodeURIComponent(keyVal[1])); break; } } } return ret; } else{//is a setter (and doesn't return), var date = new Date(); if(arguments[0] === null){//is to expire cookie 1 day ago date.setTime(date.getTime() + YESTERDAY); document.cookie = COOKIENAME + EQ + SC_SP + 'expires' + EQ + date.toUTCString() + SC_SP + 'path=/'; } else{//is to update / override current cookie value and expiration date.setTime(date.getTime() + Number(arguments[1])); document.cookie = COOKIENAME + EQ + encodeURIComponent(JSON.stringify(arguments[0])) + SC_SP + 'expires' + EQ + date.toUTCString() + SC_SP + 'path=/'; } } } };
//to create an instance of CookieMan (not to create cookie). var cookieMan = new CookieMan(); //following line returns value of current cookie held by CookieMan to var i, else it returns false. var i = cookieMan.val(); //to create / set / update CookieMan's cookie value. //1st parameter must be a valid JSON object (instead of a string) and 2nd parameter is expiration time [milliseconds] cookieMan.val({hello:'dolly'}, 60 * 1000); //to expire CookieMan's cookie cookieMan.val(null);
Try to click following buttons. You may want to close your browser / redirect to other websites and back and test "document.cookie" on your opened web Console.
Comments