sainture
10/14/2015 - 9:31 AM

cookie javascript

cookie javascript

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

// Examples
createCookie('ppkcookie','testcookie',7);

/*
If you set the number of days to 0 the cookie is trashed when the user closes the browser.
If you set the days to a negative number the cookie is trashed immediately.
*/

var x = readCookie('ppkcookie1')
if (x) {
	//[do something with x]
}

// Create cookie in JSON format
createCookie('RedeyeRecentGames','{"category":"video-slots", "game":"hall-of-gods"}',30);
var recent = JSON.parse(readCookie('RedeyeRecentGames'));