Page 1 of 1

JavaScript Cookies Set, Read, Reset, and View Cookies Rate Topic: -----

#1 kewlkreator  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 38
  • View blog
  • Posts: 1,065
  • Joined: 25-March 09

Posted 09 August 2009 - 02:31 PM

Hello. In this tutorial, I'm going to show you how to use cookies in Javascript.

Cookie?
A cookie is a small text file that contains information that can be written/read by a website. These text files may be no larger than 4kb or about 4000 characters.

Write a Cookie
To write a cookie, we can use the document.cooke statement. Lets write a cookie that stores a username:
function writeCookie() {
var username = prompt("Whats your username?", "kewlkreator");
//Gets the username
var cookieContent = "username=" + escape(username);
//Escapes the username to remove any illegal characters
document.cookie = cookieContent;
//Sets the cookie
}


Read a Cookie
To read a cookie, I'm gonna split the cookie into an array.
function readCookie() {
var wholeCookie = document.cookie;
//Grabs the whole cookie
var splitCookie = wholeCookie.split("=");
//Splits the whole cookie into an array called splitCookie
var username = splitCookie[1];
//Where splitCookie[0] is "username", splitCookie[1] holds our string
var username = unescape(username);
//Unescapes the username
alert("Your username: " + username);
//Alerts the username
}


Reset a cookie
To reset a cookie, pass the new content through a parameter like:
function setCookie(value1, value2) {
//Value 1 is the name of value2
//Value 2 is the content of value1
var cookieContent = escape(value1) + "=" + escape(value2);
//Escapes to remove all illegal characters
document.cookie = cookieContent;
}


So, to use this, we could call the function like setCookie(myname, kewl) this would set a cookie like:
document.cookie = myname=kewl

_______________________________________
<--||Extra: Alert a site's cookie--||>
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^

If you want to read a site's cookie, enter into the address bar: java script:alert(document.cookie);

This will alert the cookie content! :)

Finished
Your done! Go forth my minions! Conquer the world of cookies! :D

--Kewlkreator

Is This A Good Question/Topic? 0
  • +

Page 1 of 1