Javascript session

Store your session data in

For a long time I thought there is no such a thing call `session` in javascript, all variables and function will be clear after the page is reloaded. Not until I found this tiny javascript session library wrote by Craig Buckler.

Let’s take a look at the source code
 * Implements cookie-less JavaScript session variables
 * v1.0
 * By Craig Buckler,
 if (JSON && JSON.stringify && JSON.parse) var Session = Session || (function() {
	// window object
	var win = || window;
	// session store
	var store = ( ? JSON.parse( : {});
	// save store on page unload
	function Save() { = JSON.stringify(store);
	// page unload event
	if (window.addEventListener) window.addEventListener("unload", Save, false);
	else if (window.attachEvent) window.attachEvent("onunload", Save);
	else window.onunload = Save;

	// public methods
	return {
		// set a session variable
		set: function(name, value) {
			store[name] = value;
		// get a session value
		get: function(name) {
			return (store[name] ? store[name] : undefined);
		// clear session
		clear: function() { store = {}; },
		// dump session data
		dump: function() { return JSON.stringify(store); }


// store a session value/object
Session.set(name, object);

// retreive a session value/object

// clear all session data
// dump session data

Basically what it does is storing all your variables in json string format in the `` property which does not change when your browser goes to another page. Very clever move!!

There is also another javascript session library call `sessvars` which does the same thing but with more options. You might want to take a look at it if you have advance usage of javascript sessions.


This demo is also made by Craig Buckler.


Related posts