Javascript Cookies

A Javascript Cookies is nothing but a small piece of data that's stored in user's browser and can be picked up by the web pages when it requires. Cookies are set to expire after a certain length of time. They are limited to storing string values only. It contains some data.

  • A name-value pair containing the actual data
  • An expiry date after which it is no longer valid
  • The domain and path of the server it should be sent to

What Kinds of Data Can Be Stored in a Cookie?

A cookie is basically a string of text characters not longer more than 4 KB. Cookies are set in the form of name/value pairs, separated by semi-colons.

Cookies has some limitation, some browsers will have a limit to how many cookies they can store, usually 300 cookies or more, of which there may be 20 cookies per domain name. A total of 4 KB (after encoding) of cookies can be stored for any domain or path.

Syntax

How cookies work

A Cookie is text information that is transferred from the server to your Browser via the HTTP protocol and then stored on your hard drive. If a site uses a Cookie then everytime you visit that site, if the browser has a Cookie stored on it, it transfers that Cookie to that site. The program on the site using the Cookie then access the information and acts upon it. It is important to understand here that a Cookie will only be transfered to the site that created it. Part of the Cookie is the domain name of the site that created it as well as the path to the program that access it. Unless the domain and path match exactly as they were set, the Cookie IS NOT TRANSFERED! There is no way for someone from one site to see the contents of the Cookie from another site.

Set Cookie

In Javascript setting a cookie is very simple. Just assign the string you want for the cookie to the document.cookie property. For example, if you want to set the cookie, you can simply include the following JavaScript code.

Javascript Set Cookies Example

Read Cookie

To read a Javascript cookie, you need cookies name to read back from browser. Call this function and pass the name of the cookie. Put the name in a variable. First check if this variable has a value then do whatever is necessary.

Javascript Read Cookies Example

Delete Cookie

In Javascript delete cookie, delition of cookie is extremely simple. There are times when you may want to delete a cookie, such as when a visitor logs out of your site.

Javascript Read Cookies Example