Projects » JavaScript » PageState (cookie library)

PageState: Accessing Cookies in JavaScript

29 Jun 2005
Version 1.0
Download: pagestate.js

The PageState library provides an easy-to-use interface for accessing cookies with client-side JavaScript.

In client-side JavaScript, access to the current page's cookies is done through the document.cookie property. This interface is eccentric, and for compatibility reasons unlikely to change.

PageState provides a cleaner way to read and write cookie values for the current page, path, or domain.

Usage

Note

All names and values are escape()'d when set and unescape()'d when read.

API

PageState.getAll()
Returns all current page cookies in a dictionary. This dictionary is not "live"; changes to the dictionary will not affect page cookies, and changes to page cookies will not update existing dictionaries.
PageState.get(name[, default_])
Returns the value for the cookie with the given name. If no cookie with that name exists for the current page, returns default_ (which itself defaults to null if omitted.)
PageState.set(name, value[, options])
Sets a cookie for the current page with the given name, value, and options. options should be a dictionary with keys from the list of Cookie Options below.
PageState.remove(name[, options])
Remove the current page cookie with the given name. The path and domain options must match the options used when the cookie was created.

Cookie Options

The following optional features may be set on individual cookies.

expires
A date indicating when this cookie will be deleted. If omitted, the cookie is valid for the current browser session only. If set in the past, the cookie will be deleted on the client.
expires can be either a Date object or a string or number that used to construct a new Date. (The ultimate format for this value is the output of Date.toGMTString().)
path
The URL prefix on which this cookie is valid. The cookie will be sent for all URLs that start with the given path. If no path is given the cookie will be sent for all URLs on the current domain, equivalent to a path of "/".
domain
The domain or sub-domain on which this cookie is valid. If omitted, the cookie will be set for the current domain. If you set a cookie while viewing a page at www.adamv.com and domain isn't set, the cookie will be valid for all sub-domains of adamv.com.
secure
If true the cookie will only be sent to the server over matching paths and domains over the HTTPS protocol, but not HTTP.

Contact Information