How to Get and set cookies in javascript
For years, many web developers have needed to store data on the client. Before the advent of HTML5 and its new mechanisms, every developer used cookies to achieve this goal. Unfortunately, working with cookies in JavaScript can cause a lot of headaches. This article discusses what cookies are, and how you can build functions to create, retrieve, and delete them.
A cookie is a piece of data which is sent from a website and stored locally by the user’s browser. Cookies are needed because HTTP is stateless. This means that HTTP itself has no way to keep track of a user’s previous activities. One way to create state is by using cookies.
The structure of a cookie is really simple. It’s nothing but several key-value pairs. Pairs are separated by semicolons, while the equal sign character separates the key from its value. A cookie can optionally have an expiration date, after which it’s deleted. If an expiration date isn’t provided, the cookie will last until the session or browser is closed. If you set the expiration date in the past, the browser will delete the cookie. Please note that the format of the date is important, as it has to be in UTC/GMT. Moreover, you can specify a domain and a path where the cookie can be read and written. By default the path value is ‘/’, meaning that the cookie is visible to all paths in a given domain. If you don’t specify the domain, it will belong to the page that set the cookie. The way you set these data also matter. The order should be:
key-value;expiration_date;path;domain;.
var cookies = {
s: function (c_name, value, exdays, extime) {
if (extime == "" || extime == null || typeof (extime) == "undefined")
extime = false;
var exdate = new Date();
if (extime) {
exdate.setMinutes(exdate.getMinutes() + extime);
}
else {
exdate.setDate(exdate.getDate() + exdays);
}
var c_value = encodeURIComponent(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()) + "; path=/";
document.cookie = c_name + "=" + c_value;
},
swd: function (c_name, value, exdays, extime) {
if (extime == "" || extime == null || typeof (extime) == "undefined")
extime = false;
var exdate = new Date();
if (extime) {
exdate.setMinutes(exdate.getMinutes() + extime);
}
else {
exdate.setDate(exdate.getDate() + exdays);
}
var c_value = value + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()) + "; path=/";
document.cookie = c_name + "=" + c_value;
}, g: function (c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = $.trim(x);
if (x == c_name) {
return decodeURIComponent(y);
}
}
}, e: function (name) {
this.s(name, "", 0, -1);
}
};
No comments: