This example will show you how to maintain a series of persistent state variables on all pages of your web site. The idea is that you will maintain a single set of variables to keep track of any of the information that any of your pages may need to function. Each page, upon loading, will call a function to restore these variables from cookie storage. If no cookie is found then a default value will be used instead. (This will usually happen only the first time the user visits one page of the site, to initialize all the values.) When a page is finished (i.e., in the onUnload event handler) all the current values of the variables will be saved in cookies, ready to be read by the next page that loads. Presumably some of the pages will have ways to change some of the state variable values -- perhaps based on form input, perhaps randomly, etc.

Because all your pages will share the same set of state variables, and will do the same things when they load and unload, it makes sense to store the necessary functions in an external javascript file. The file used in this example is state.js. You may use it as a template for your own pages if you wish. Storing all your information in one place simplifies things, because you only have to get it right once. Note that this example also relies on the generic cookie processing functions cookies.js, so you will need to include that file as well.

The information stored in your state variables could be many things: user customizations to the page appearance, other preferences, a record of past activity, etc. This particular example shows how state might be used as part of a game. In this game the user can travel from room to room, and may carry certain items with them. Each room is a single page. The record of the set of items carried, along with any other important actions that have been carried out (like throwing a switch in a different room, for example) will form the state of the game. Depending on this state, certain options may or may not be shown to the user.

Note that for this example, and for any application where you want to use load-time scripts with document.writeln() to put content into your page, you will have to call the restoreState() function before any uses of the state variables. This means that calling it in the onLoad event handler of the body is actually too late, because that event triggers only when the entire page has been loaded and interpreted. Instead you can just put the call to restoreState() at the beginning of a script section in the header of your page, as you see it done in this example. If you are not using load-time scripts, then it is probably safe to put the call to restoreState() in the onLoad event handler.


An Example Game