Skip to content

Instantly share code, notes, and snippets.

@ali-master
Created February 18, 2017 04:11
Show Gist options
  • Save ali-master/20039240fa549296db07555c21312502 to your computer and use it in GitHub Desktop.
Save ali-master/20039240fa549296db07555c21312502 to your computer and use it in GitHub Desktop.
JavaScript Cookies

JavaScript Cookie

var PryCookie = {
	set: function(name, value, path, domain, expire) {
		var this_path = '';
		if (path != undefined) {
			this_path = '; path=' + path;
		}
		var this_domain = '';
		if (domain != undefined) {
			this_domain = '; domain=' + domain;
		}
		var this_expire = '';
		if (expire != undefined) {
			var d = new Date();
			d.setTime(d.getTime() + (86400000 * parseFloat(expire)));
			this_expire = '; expires=' + d.toGMTString();
		}
		return (document.cookie = name + '=' + value + this_path + this_domain + this_expire);
	},
	get: function(name) {
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
		return (cookie ? unescape(cookie[2]) : null);
	},
	erase: function(name) {
		var cookie = PryCookie.get(name) || true;
		PryCookie.set(name, '', '', '', -1);
		return cookie;
	},
	accept: function() {
		if (typeof navigator.cookieEnabled == 'boolean') {
			return navigator.cookieEnabled;
		}
		PryCookie.set('_test', '1');
		return (PryCookie.erase('_test') === '1');
	}
};

Usage

# Set Cookie
PryCookie.set(name, value);

# Get Cookie Value
PryCookie.get(name);

# Erase Cookie
PryCookie.erase(name);

# Check Browser Supports Cookies
PryCookie.accept(); // return Boolean
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment