Working with cookies from javascript

Working with cookies from javascript

Web browsers allow a small amount of information called cookies to be stored on the user client. Using them, it’s convenient to store user settings, for example, the selected design theme, products viewed by him, etc. Cookies have their own advantages and disadvantages, like everything in this world.

Web browsers allow a small amount of information called cookies to be stored on the user client. Using them, it’s convenient to store user settings, for example, the selected design theme, products viewed by him, etc. Cookies have their own advantages and disadvantages, like everything in this world. The advantages include the fact that you do not need to store not very important information on the server. This reduces the load on the server and saves disk space on it.

But unfortunately, there are more shortcomings. Cookies can be accessed by any other script running on the user's computer (even if he did not set Cookies), therefore confidential information cannot be stored there, for example, authentication sign, credit card numbers, passwords, etc. In addition, if the user launches another browser on the computer, the data stored in cookies will become inaccessible.

Before you start using cookies, you need to check whether their browser supports the client:

if (navigator.cookieEnabled) {

// Cookies поддерживаются, можно устанавливать и читать их

}

Cookies can be set by assigning a value to the cookie property of the document object in the following format:

document.cookie = "<Имя>=<Значение>; [expires=<Дата>;] [domain=<Имя домена>;] [path=<Путь>;] [secure;]";

In the simplest case, you need to specify the pair <Name> = <Value>. In a slightly more complex one, the expiration date of the validity period. The date should be indicated only in this format:

Mon, 23 Feb 2019 00:05:07 GMT

After this date, the cookie will be deleted. You can get the date in this format (so as not to create it manually) using the setTime () method and the toGMTString () method. Example:

let newDate = new Date();

newDate.setTime(newDate.getTime() + 36000000); // Срок действия Cookie - 10 часов

let endDate = newDate.toGMTString(); // Дата удаления cookies

Cookies can be read by calling document.cookie. The returned string will contain all cookies set in the format "name1 = value1; name2 = value2".

To delete a cookie, you must set it with an expired date. There is no other way.

To make cookies easier, you can use the functions below. Using them, you can quickly set, read and delete cookies.

function setCookie(name, value, expire, path, domain, secure) {

if(!name || !value) {

return false;

}

var str = name + '=' + encodeURIComponent(value);

 

if(expire) {

str += '; expires=' + expire.toGMTString();

}

 

if (path) {

str += '; path=' + path;

}

 

if(domain) {

str += '; domain=' + domain;

}

 

if (secure) {

str += '; secure';

}

 

document.cookie = str;

return true;

}

 

function getCookie(name) {

var pattern = "(?:; )?" + name + "=([^;]*);?";

var regexp = new RegExp(pattern);

 

if(regexp.test(document.cookie)) {

return decodeURIComponent(RegExp["$1"]);

}

 

return false;

}

 

function deleteCookie(name, path, domain) {

setCookie(name, null, new Date(0), path, domain);

return true;

}

Functions are started as follows:

- Set cookies without parameters, only name and value

setCookie ('color', 'red');

- We make reading Cookie:

var color = getCookie ('color');

- Output Cookie:

window.alert (color);