Changes

Jump to: navigation, search

Understanding JavaScript Cookies

1,391 bytes added, 15:14, 18 May 2007
Cookie ''domain'' Setting
Similarly to the path setting, cookies are only accessible to web pages residing on the server domain from which the cookie was originally created. For example acookie created by a web page residing on www.techotopia.org is not, by default, accessible to a web page hosted on www.linuxtopia.org. Access to the cookie from web pages on linuxtopia.org can be enabled with a ''domain=linxutopia.org''.
 
== Creating a Cookie ==
 
Now that we have an understanding of what cookies are and how theya re structured we can now looka t how to create one. As mentioned previously in this chapter cookies are created using the ''cookie'' property of the JavaScript ''Document'' object. In the following example we will prompt the user for their name and then write that information to a cookie on their computer:
 
<pre>
<html>
<head>
<title>JavaScript Cookie Example</title>
<script language=javascript type="text/javascript">
 
 
function writeCookie( )
{
name = document.orderForm.nameField.value;
document.cookie = "yourName=" + name;
}
 
</script>
</head>
 
<body>
<form action="" name="orderForm">
Enter your name: <input type="TEXT" name="nameField"/>
<input type="BUTTON" value="Write Cookie" onClick="writeCookie()" />
</form>
 
</body>
</html>
</pre>
 
== Reading a Cookie ==
 
Once a cookie is written we can then read tha cookie back. We will now extend our example to add a "Read Cookie" button which will read the value of the cookie and write it out to the browser document. Note that the value/pair of the cookie is actually a JavaScript ''String'' object so we can use the String ''split()'' method to divide the ''name=value'' at the ''='' and extract just the value (see [[JavaScript String Object]]). For example:
 
<pre>
var yourName = document.cookie.split("=")[1];
</pre>

Navigation menu