Writing and Reading and Deleting a Cookie on the Browser

Creating Cookies with a <META> Tag

Listing 1. Creating a Cookie that Is Valid Until a Certain Date

Listing 2. Creating a Cookie that Is Only Valid Until the Browser Is Closed

Creating Cookies with document.cookie

On the client side, JavaScript is used to create cookies. There are several ways to do this. The easiest way is to use document.cookie. The following is the syntax for creating a cookie this way:

document.cookie = "cookieName=cookieValue 
  [; expires=timeInGMTString] 
  [; path=pathName] 
  [; domain=domainName] 
  [; secure]"

The code in Listing 3 creates a cookie called Quantity with a value of 7 that lives as long as the browser is open.

Listing 3. Creating a Cookie with document.cookie

<HTML> 
<HEAD> 
<TITLE>Creating a cookie with document.cookie</TITLE> 
<SCRIPT LANGUAGE="JavaScript"> 
document.cookie="Quantity=7"; 
</SCRIPT> 
</HEAD> 
<BODY> 
This page creates a cookie on the client side. 
Make sure that your browser is set to accept cookies. 
</BODY> 
</HTML>
 

Writing and Reading Cookies

Listing 4. Writing and Reading Cookies

Deleting a Cookie

You don't really delete a cookie, you just make it expire by setting the expiration date to the first second of the year 1970, as in the deleteCookie function in Listing 5. Note that the function uses the getCookie function from Listing 4, so you need to paste the getCookie function in your page as well.

Listing 5. Deleting a Cookie

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章