2 min read

JavaScript Cookies

Cookies let you store user information in web pages.When a browser requests a web page from a server, cookies belonging to the page are added to the request. This way the server gets the necessary data to "remember" information about users.
JavaScript Cookies

Cookies are data, stored in small text files, on your computer.

When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.

Cookies were invented to solve the problem "how to remember information about the user":

  • When a user visits a web page, his/her name can be stored in a cookie.
  • Next time the user visits the page, the cookie "remembers" his/her name.

Cookies are saved in name-value pairs like:

username = John Doe

Create a Cookie with JavaScript

JavaScript can create, read, and delete cookies with the document.cookie property.

With JavaScript, a cookie can be created like this:

document.cookie = "username=John Doe";

Read a Cookie with JavaScript

With JavaScript, cookies can be read like this:

var x = document.cookie;

document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;

Delete a Cookie with JavaScript


Deleting a cookie is very simple.You don't have to specify a cookie value when you delete a cookie.Just set the expires parameter to a past date:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

You should define the cookie path to ensure that you delete the right cookie.

https://static.javatpoint.com/javascriptpages/images/javascript-cookies.png
JavaScript Cookies
https://www.w3schools.com/js/js_cookies.asp

#JavaScript #Cookies #Document #Probyto #Probyto AI

Subscribe and follow us for latest news in Data Science and Machine learning and stay updated!

Facebook: https://facebook.com/probyto
Twitter: https://twitter.com/probyto
LinkedIn: https://linkedin.com/company/probyto
Instagram: https://instagram.com/probyto