Latest web development tutorials
×

JavaScript Tutorial

JavaScript Tutorial JavaScript Introduction JavaScript usage JavaScript Output JavaScript grammar JavaScript Statement JavaScript Notes JavaScript variable JavaScript type of data JavaScript Object JavaScript function JavaScript Scope JavaScript event JavaScript The string JavaScript Operator JavaScript Comparison JavaScript If...Else JavaScript switch JavaScript for JavaScript while JavaScript Break & Continue JavaScript typeof JavaScript Type conversion JavaScript Regular Expressions JavaScript error JavaScript debugging JavaScript Variable promotion JavaScript Strict mode JavaScript Use errors JavaScript Form validation JavaScript Keep the keyword JavaScript JSON JavaScript void JavaScript Code specification

JS function

JavaScript Function definition JavaScript Function parameter JavaScript Function call JavaScript Closure

JS HTML DOM

DOM Introduction DOM HTML DOM CSS DOM event DOM EventListener DOM element

JS Advanced Tutorial

JavaScript Object JavaScript Number JavaScript String JavaScript Date JavaScript Array JavaScript Boolean JavaScript Math JavaScript RegExp Object

JS Browser BOM

JavaScript Window JavaScript Window Screen JavaScript Window Location JavaScript Window History JavaScript Navigator JavaScript Pop-ups JavaScript Timing events JavaScript Cookies

JS Library

JavaScript Library JavaScript test jQuery JavaScript test Prototype

JS Examples

JavaScript Examples JavaScript Object instance JavaScript Browser object instance JavaScript HTML DOM Examples JavaScript to sum up

JS Reference Manual

JavaScript Object HTML DOM Object

JavaScript Cookies


Cookies for user information is stored web pages.


What are Cookies?

Cookies are data stored in a text file on your computer in.

When the web server sends the web page to the browser after the connection is closed, the server does not record user information.

Cookies role is to solve the "how to record the client user information":

  • When a user visits a web page, his name can be recorded in a cookie.
  • When the next time the user access the page, you can read the user access records in a cookie.

Cookies with name / value pairs are stored as follows:

username=John Doe

When a browser requests a web page from the server, the cookies belonging to the page will be added to the request. The server to get the user information in this way.


Use JavaScript to create Cookie

JavaScript document.cookie property can be used to create, read, and delete cookies.

JavaScript, create a cookie as follows:

document.cookie="username=John Doe";

You can also add a cookie expiration time (in UTC or GMT time). By default, cookie deleted when the browser is closed:

document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 GMT";

You can use the path parameter tells the browser cookie path. By default, cookie belongs to the current page.

document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";

Use JavaScript to read Cookie

In JavaScript, you can use the following code to read cookies:

var x = document.cookie;

Note document.cookie string will return all manner of cookies, type Format: cookie1 = value; cookie2 = value; cookie3 = value;


Modify Cookie using JavaScript

In JavaScript, modify cookies similar to creating cookies, as follows:

document.cookie="username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";

The old cookie will be overwritten.


Remove Cookie using JavaScript

Remove cookie is very simple. You only need to set the parameters for the previous time expires, as shown below, is set to Thu, 01 Jan 1970 00:00:00 GMT:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";

Note that when you delete without specifying the value of the cookie.


Cookie string

document.cookie property looks like an ordinary text string, in fact it is not.

Even if you write a complete cookie string document.cookie, when you re-read the cookie information, cookie information is name / value pairs in the form of impressions.

If you set a new cookie, old cookie will not be overwritten. The new cookie will be added to document.cookie, so if you re-read document.cookie, you will receive the data as follows:

cookie1 = value; cookie2 = value;

If you need to find a specific cookie value, you must create a JavaScript function to find the value of the cookie in the cookie string.


JavaScript Cookie instances

In the following example, we will create a cookie to store the name of the visitor.

First, visitors to the web page, he will be asked to fill in their name. The name will be stored in a cookie.

The next time you access the page a visitor, he will see a welcome message.

In this example, we'll create three JavaScript functions:

  1. Setter cookie value
  2. Get cookie function values
  3. Function detects cookie value

Setter cookie value

First, we create a function for storing the visitor's name:

function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}

Function resolution:

More than one function parameters, cookie name for the cname, cookie value cvalue, and set the cookie expiration time expires.

This function sets the cookie name, cookie value, cookie expiration time.


Get cookie function values

Then, we create a function that returns the user to specify the value of the cookie:

function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
  {
  var c = ca[i].trim();
  if (c.indexOf(name)==0) return c.substring(name.length,c.length);
  }
return "";
}

Function resolution:

Parameters cookie name is cname.

Create a text variable is used to retrieve the specified cookie: cname + "=".

Use semicolons to separate document.cookie string and assigned to a string array divided ca (ca = document.cookie.split ( ';')).

Cycle ca array (i = 0; i <ca.length; i ++), and then reads each value in the array, and the removal of trailing spaces (c = ca [i] .trim ()).

If you find a cookie (c.indexOf (name) == 0), returns the cookie value (c.substring (name.length, c.length).

If you do not find the cookie, returns "."


Function detects cookie value

Finally, we can create a function to detect whether the cookie is created.

If you set a cookie, it will display a greeting message.

If you do not set a cookie, it will display a pop for inquiring visitor's name and call the visitor's name setCookie function storage 365 days:

function checkCookie()
{
var username=getCookie("username");
if (username!="")
  {
  alert("Welcome again " + username);
  }
else
  {
  username = prompt("Please enter your name:","");
  if (username!="" && username!=null)
    {
    setCookie("username",username,365);
    }
  }
}


Complete example

Examples

function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
  {
  var c = ca[i].trim();
  if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}

function checkCookie()
{
var user=getCookie("username");
if (user!="")
  {
  alert("Welcome again " + user);
  }
else
  {
  user = prompt("Please enter your name:","");
  if (user!="" && user!=null)
    {
    setCookie("username",user,365);
    }
  }
}

try it"

The following examples execute checkCookie () function when the page is loaded.