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. 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);

Popular Posts

My most popular posts

Maximum productivity on remote job
Business

Maximum productivity on remote job

I started my own business and intentionally did my best to work from anywhere in the world. Sometimes I sit with my office with a large 27-inch monitor in my apartment in Cheboksary. Sometimes I’m in the office or in some cafe in another city.

Hello! I am Sergey Emelyanov and I am hardworker
Business PHP

Hello! I am Sergey Emelyanov and I am hardworker

I am a programmer. I am an entrepreneur in my heart. I started making money from the age of 11, in the harsh 90s, handing over glassware to a local store and exchanging it for sweets. I earned so much that was enough for various snacks.

Hire Professional CRM developer for $25 per hour

I will make time for your project. Knowledge of Vtiger CRM, SuiteCRM, Laravel, and Vue.js. I offer cooperation options that will help you take advantage of external experience, optimize costs and reduce risks. Full transparency of all stages of work and accounting for time costs. Pay only development working hours after accepting the task. Accept PayPal and Payoneer payment systems. How to hire professional developer? Just fill in the form

Telegram
@sergeyem
Telephone
+4915211100235