How to Write a Cookie-less Session Library for JavaScript

In my previous post, Cookie-less Session Variables in JavaScript, we discovered how JavaScript session data could be saved to the window.name property. Today, we create a JavaScript library to exploit this property.

The private Save() function assigns the serialized the ‘store’ object string to the window .name property. The following three lines define a cross-browser event which calls the Save function when the page is unloaded. Your pages can therefore modify the ‘store’ as much as necessary, but the heavy work of serializing and saving only occurs at the last possible moment.

Finally, we have our four public set, get, clear and dump functions which handle the store object accordingly. The Session.get() method will return a JavaScript ‘undefined’ value if a session name can not be found.

I hope you find the code useful. Feel free to use it in your own projects.

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

kylefarris

That’s actually pretty interesting. Would have never thought of it. Learn something new every day, I guess…