w3resource logo


JavaScript Reading Cookies

JavaScript : Reading Cookies

<<PreviousNext>>

Reading Cookies

When a browser opens a web page, the browser reads the cookies (provided it has already stored it) that has stored in your machine. We used document.cookie to retrieve the information about the cookie.

Example :

In the following web document we receive a name from the visitor and stored it in the cookie called "Name".

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>JavaScript creating cookies - receive real data. example1</title>
</head>
<body>
<h1 style="color: red">JavaScript creating cookies, receive real data. - example1</h1>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
var visitor_name = prompt("What's your name?","");
var curdate = new Date();
curdate.setMonth(curdate.getMonth() + 6);
var cookie_date  = curdate.toUTCString();
final_cookie = "my_cookie=" + encodeURIComponent(visitor_name) + ";expires_on = " + cookie_date; 
document.cookie = final_cookie;
alert(final_cookie); 
//]]>
</script>
</body>
</html>

View the example in the browser

Example : Retrieves values from cookie

In the following web document we will read the stored cookie and retrieves it's value.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>JavaScript : Retrieve values from a cookie - example1</title>
</head>
<body>
<h1 style="color: red">JavaScript : Retrieve values from a cookie - example1</h1>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
var search_cookie = "my_cookie" + "="
if (document.cookie.length > 0) 
{
// Search for a cookie.
offset = document.cookie.indexOf(search_cookie)
if (offset != -1)
{
offset += search_cookie.length 
// set index of beginning of value 
end = document.cookie.indexOf(";",offset)
if (end == -1) 
{
end = document.cookie.length
}
alert(decodeURIComponent(document.cookie.substring(offset, end)))
}
}
//]]>
</script>
</head>
</body>
</html>

View the example in the browser

<<PreviousNext>>

Rate this tutorial


Your Rating: not set

Share this tutorial

RSS Feed