I was going to write one long blog post about advanced handling of browsing history, but then I decided to split this into two separate articles.

In this article I’ll represent a small JavaScript snippet I created for handling client-side session variables without cookies or Local Storage.

The snippet, Session.js, works on all modern browsers that support JSON natively. And if you want to extend it to work on browsers like Internet Explorer 6, you can use custom JSON implementation (eg. Sitepoint: Cross-browser JSON Serialization in JavaScript).

The reason I wrote this is simple – sometimes you just want to persist client-side variables during the whole session. In general, cookies are OK, but I personally dislike them to be used as very temporary data storages. I just don’t want to pollute cookie with (secondary) data that isn’t ever meant to be used after the session. Beside, cookies do not accept larger quantities of data.

Therefore I’m using window.name property. This property will exist during the whole session, and is automatically emptied when user closes the window or moves to another domain.

There are also other implementations of the very same topic, such as Thomas Frank’s sessvars.

Methods

There are following methods:

Session.setVar(string name, mixed value)

This sets the variable. You can add any type of value (number, string, boolean, object).

Session.getVar(string name)

This returns the variable. If such variable doesn’t exist, this returns false.

Session.removeVar(string name)

This removes the variable. If such variable doesn’t exist, this returns false.

Session.subscribe(string name, function callback)

This attaches a function to the variable. So whenever variable is set on the document, or is already set earlier during session, subscribed functions are fired. However, function won’t be fired when variable is removed, but the function itself will stay attached on the variable and fired if the variable is set again.

You can add a “namespace” for functions to distinct them for unsubscribing. This is done by adding a period on variable name: Session.subscribe(“foo.alertVariable”, function() { alert(Session.getVar(“foo”); });.

Session.unsubscribe(string name)

This simply unsubscribes certain function attached to the variable, eg Session.unsubscribe(“foo.alertVariable”).

Source Code

You can get the source code from here.

There is also very small demonstration available in here.