Cookies in Javascript

A cookie is a variable that is stored on the visitor’s computer. Each time the same computer requests a page with a browser, it will send the cookie to the client machine. Cookies are KeyValue Pairs.

Create a Cookie.

This code will prompt for a name, and save the username in a cookie.

var username = prompt("Enter your name");
document.cookie = "username=" + username;

Reading a cookie

This code will read the value from the cookie and alert the username.

var cookiename = "username="
var startcookie = document.cookie.indexOf(cookiename) + cookiename.length;
var endcookie = document.cookie.length;
alert(document.cookie.substring(startcookie,endcookie));

This is a simple example, you can also look for expriy date of cookie, is a cookie secure etc.

To disble cookies in browser(It depends on the Browser)

Microsoft Internet Explorer 6

Tools > Internet Options > Privacy > Click advanced and check Override Automatic cookie handling checkbox, and choose the radio buttons.

This entry was posted in Javascript and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>