Home » javascript » Cookies in JavaScript

Cookies in JavaScript

What are Cookies?

Normally, Cookies store user information in small text files.on your computer.

A cookie is a piece of data that is stored on your browser to be accessed by your browser. Cookies are also saved as key/value pairs.

Cookies will remember information about the user, when server forgets everything about the user after the connection is shut down.

  • When a user visits a web page, The name of user can be stored in a cookie.
  • Next time the user visits the page, the cookie “remembers” the name.

How It Works ?

Server sends some data to the visitor’s browser in the form of a cookie. The browser may accept the cookie. When the visitor go to another page, the browser sends the same cookie to the server.

Cookies are a plain text data record of 5 variable −

  • Expires − The date the cookie will expire
  • Domain − The domain name of thewebsite.
  • Path − The path to the directory or web page that set the cookie.
  • Secure − The cookie may only be retrieved with a secure server.
  • Name value – Cookies are set and retrieved in the form of key-value pairs

Create a Cookie with JavaScript

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

A cookie can be created like this:

document.cookie = “username=Ram Das”;

Example

Read a Cookie with JavaScript

With JS, cookies can be read like this:

var x = document.cookie;

Example

Change a Cookie with JavaScript

With JS, cookies can be changed like this:

document.cookie = “username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/”;

Example

In this example the cookie extend the expiry date by 1 Month.

Delete a Cookie with JavaScript

With JS, cookies can be delete like this:

Just set the expires parameter to a passed date:

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

Example

 Full Example

Please follow and like us:
error