Javascript session

Store your session data in window.name

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, Optimalworks.net
 *
 */
 
 if (JSON && JSON.stringify && JSON.parse) var Session = Session || (function() {
 
	// window object
	var win = window.top || window;
	
	// session store
	var store = (win.name ? JSON.parse(win.name) : {});
	
	// save store on page unload
	function Save() {
		win.name = 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); }
 
	};
 
 })();

Usage

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

// retreive a session value/object
Session.get(name);

// clear all session data
Session.clear();
 
// dump session data
Session.dump();

Basically what it does is storing all your variables in json string format in the `window.name` 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.


Demo

This demo is also made by Craig Buckler.

References


Related posts