Advanced JavaScript: Storage — SessionStorage

Session Storage

Learning outcomes:

  • What is sessionStorage
  • How sessions work
  • Storing, retrieving and removing data
  • The storage event

Introduction

In the previous chapter we saw, in detail, how localStorage works in browsers and how it takes over cookies to persistently store information used by the client only.

In particular we saw how to add, update and remove data from storage in two ways: the object property-access syntax and methods defined by the Storage API. And we saw even more utilities available to the API such as the clear() method and the length property.

Now, in this chapter we sahll learn the second form of web storage - the sessionStorage object. Owing to the fact that it's also based on the Storage API, almost all the concepts we learnt in localStorage essentially apply here as well.

So, if you have read the previous chapter and are familiar with localStorage, this chapter will be just a new way to look at all those utilities; this time storing data from session to session.

Let's dive right in!

What is sessionStorage?

Just like localStorage, sessionStorage is a property of the window object that is based on the Storage interface.

However, unlike localStorage, it doesn't store data persistently - rather the storage remains in place only for a browsing session.

Therefore, to understand how sessionStorage works, one must first understand what is meant by a browser session.

Essentially, a browser session defines all the period of time a user is continuously engaged within a browser tab.

For instance, if you open a new browser tab, visit the webpage www.example.com, and then from there visit its store at www.example.com/store, and then from there to another link www.someotherlocation.com, and finally back to the previous website at its checkout at www.example.com/checkout (in that same tab) - all what you're doing is regarded as a single session.

You're going from one page to another one, and then to another one and so on and so forth, all in one single browser tab - and hence in one single browser session.

The moment you close the tab, the session ends and a new one starts.

We know that sessionStorage stores data for a single session. This means that the moment we close the tab, all our data is cleared away from sessionStorage.

So, to boil it down,

sessionStorage is a Storage object available on window, that allows data to be stored only for the duration of a session.

With this setup in place, let's move on and explore the utilities on sessionStorage. Note that all of them operate exactly as they do on localStorage - if you know localStorage, you can easily work with sessionStorage and vice versa.

Storing and retrieving data

To store data in sessionStorage we can use either of the two ways we saw in the previous chapter, namely:

  1. Object property-access syntax
  2. Methods defined by the Storage API

For example, to store a key x with a value of 10, we can use either the traditional object property-access syntax, as shown below:

JavaScript
sessionStorage.x = 10; // dot notation

/* can also be expressed as */
sessionStorage["x"] = 10;

Or we can use the setItem() method, passing it the key and the value as arguments:

JavaScript
sessionStorage.setItem("x", 10);

In both these code snippets, the numeric value 10 is first coerced into a string and then put in storage.

Although it didn't happen in this example, if we provide a non-string key to setItem(), it's also coerced into a string, just like the value argument is. And obviously, this is also the case for bracket notation.

Now after setting the key-value pair, it's typical to retrieve it at some point in the future.

To do so, once again, we can use either of the two ways listed above.

In the object property-access syntax, we simply write an access expression (in dot or bracket notation) to retrieve the key's value:

JavaScript
console.log(sessionStorage.x); // "10"

// can also be expressed as
console.log(sessionStorage["x"]); // "10"

Similarly, in the second way we call the method getItem(), passing it the key whose value we want to retrieve, as shown below:

JavaScript
console.log(sessionStorage.getItem("x")); // "10"

Both of these are acceptable ways to set and get storage data, however the latter is generally preferred.

Removing data

Removing data from sessionStorage is, obviously, done exactly how we remove data from localStorage.

Either use the delete operator in a sense that you're deleting a property from sessionStorage. Otherwise, use the method removeItem(), passing it the key whose data you want to remove.

Both these ways to remove the key x from storage, that we created just right now, are illustrated below.

First, with the delete operator:

JavaScript
delete sessionStorage.x;

// same as
// delete sessionStorage["x"];

Now with the removeItem() method:

JavaScript
sessionStorage.removeItem("x");
For elaborate details of what happening in both these code snippets (although there isn't much happening!), please refer to the previous chapter on localStorage.

As we saw in the previous chapter, the behavior of delete isn't consistent in some situations such as when we delete a non-existent property from an object, and that some browsers don't support delete statements on Storage objects.

In contrast, removeItem() clears away all these problems, and has a decent support across many old browsers as well. Thus, methods are generally preferred over the property-access syntax while working with web storage.

Clearing everything

Akin to how it behaves with localStorage, the method clear() serves to clear all data when invoked on sessionStorage.

In other words, calling clear() results in length becoming equal to 0.

Consider the code below:

JavaScript
sessionStorage.a = 10;
sessionStorage.b = 20;

console.log(sessionStorage.length); // 2

// remove everything
sessionStorage.clear();

console.log(sessionStorage.length); // 0

First we create two keys a and b on sessionStorage and then log its length, which turns out to be 2.

After that we call clear(), and finally log sessionStorage.length once more, which this time turns out to be 0 - everything has been removed.

Now if we retrieve the keys a or b using getItem(), we simply get null returned.

JavaScript
// everything has been deleted
console.log(sessionStorage.a); // null
console.log(sessionStorage.b); // null

The storage event

Since sessionStorage has a different lifetime and scope as compared to localStorage, handling the storage event fired via a sessionStorage change is quite tedious.

We can't open a page in two separate tabs, perform a query in one and then handle the storage event in the other - it's just not how sessionStorage works!

Rather what we ought to do to handle storage is to first embed an iframe in a page, make the storage change in the iframe and then hear for the change, via the onstorage handler, in the outer window.

Apart from the handler we can also use the addEventListener() method to listen for the storage event.

Let's see an example.

We start by creating an HTML page with the following content.

HTML
<iframe></iframe>
<script>
    window.onstorage = function(e) {
        alert("Storage changed!")
    }
</script>

First we have an <iframe> element where our storage query will be performed, and then a <script> with some code to handle the storage event (occuring on the main page).

After this what we simply need to do is perform some sessionStorage queries inside the iframe.

This can be easily done on-the-go from the browser's Developer Tools as well; but as a widely available method we put all the actionable stuff right on the document, far from just a click!

The following page is requested for in the iframe where each time, when we click the button, a key x stored on sessionStorage is changed, causing a storage event to be fired.

HTML
storage-changer.html
<button>Change sessionStorage</button>
<script>
    var i = 0;
    var button = document.getElementsByTagName("button")[0];

    button.onclick = function(e) {
        sessionStorage.x = i++;
    }
</script>
For more info on how to work with getElementsByTagName(), please refer to HTML DOM Accessing Elements.

This event is caught by the outer main window where we get an alert "Storage changed!".

The main window now looks something like:

HTML
<iframe src="storage-changer.html"></iframe>
<script>
    window.onstorage = function(e) {
        alert("Storage changed!")
    }
</script>

View the live demonstration in the link below:

Live Example

If no alert appears on the first click, it may be the case that your sessionStorage object already has a key x with the value of 0; in which case the assignment sessionStorage.x = i++ (with i = 0) wouldn't incur any change.

For a more practical and vivid illustration of this idea consider the following:

Live Example

When a page is visited via a link on another page with some sessionStorage data, the sessionStorage data is copied over to the visited page.

In this case, when we click the link above, sessionStorage of this page is copied over to the destination page. Remember this!

And this completes the web storage API!