Cookie-less Session Variables in JavaScript

    Craig Buckler
    Share

    the (JavaScript) Cookie MonsterCookies may be delicious delicacies, but they can leave a nasty taste if you don’t cook them correctly! Cookies can be blocked by the user, storage space is limited to four 20Kb cookies per domain, only strings can be used, paths can cause confusion, and the data is normally passed as plain text in the HTTP header. Often, cookies can be overkill for client-side-heavy applications that need to save temporary state data.

    Fortunately, there is a solution that allows you to store JavaScript data within the browser. The data is retained between page loads, it’ll survive page back/next events (even away from the domain), it does not require plugins or off-line storage facilities, it’ll hold at several megabytes of information, it is never transmitted to the server, and works in every browser. Bizarrely, it works by exploiting the window.name property (or window.top.name if you’re using multiple frames).

    It’s rare for developers set the window.name property. Generally, it’s only required when you’re manipulating frames or pop-up windows. Even though I’d hope you weren’t doing that, you do not normally need to define a name for an application’s starting window. Although the name property is still a string, it can hold several megabytes of data. Some versions of Opera limit it to around 2Mb but most browsers offer 10MB or more.

    It’s easy to try for yourself. Insert the following JavaScript code into a page on your site:

    
    window.name = "This message will survive between page loads.";
    

    Now add the following code to any other page:

    
    alert(window.name);
    

    Navigate from the first page to the second and you’ll find that the message data is retained.

    As normal, there are a number of caveats:

    1. The window.name property can be analysed and changed if you navigate to page on another website. That’s easily thwarted by not providing external links within your application’s main window. However, to be on the safe side, don’t use window.name for storing secure data (unlikely to be a major problem for a client-side-only temporary data store).
    2. window.name can only store strings. What if we need to save other data types or even complex objects? Serialization is the answer and, fortunately, we have already developed cross-browser code to generate JSON strings from any JavaScript object.

    See also: How to Write a Cookie-less Session Library for JavaScript.