HTML5 client-side storage tutorial: Beyond cookies

1 2 3 4 5 6 Page 2
Page 2 of 6

Both storage objects provide methods to set values, get values, remove a key, retrieve a key for a position in the list, and clear all the key/value pairs in the storage object. The methods and properties of each storage object type are the same, because they are inherited from the same Storage interface defined in the Web Storage specification:

  • setItem(key,value): Sets the key/value pair passed as parameters. If the key exists, then the value is updated with the value passed.
  • getItem(key): Returns the value for the key passed as a parameter.
  • removeItem(key): Removes the key/value pair as defined by the key passed.
  • key(n): Returns the name of the key for the index provided.
  • clear: Removes all key/value pairs.
  • length: Provides the number of key/value pairs in the storage list.

To set an item, you call setItem and provide a key and a value to be set:

setItem(key, value)

Here are the parameters:

  • key: The key to file the string value under
  • value: The value to be stored with the file

The value is a string, so if you are storing a number, it will be treated as a string in the storage and will need to be converted back to the proper data type when retrieved. The key and value will then be stored in no particular order in the list of key/value pairs in the browser storage for the domain that the page has been loaded from.

If you set the item with a key that already exists, then the value of that key will be updated with the new value provided. Thus, the setItem method acts as both a create method and an update method. To store the value book under the key source in the session storage, you would make the following call in JavaScript:

sessionStorage.setItem('source', 'book');

The setItem method does not have a return value, so to protect against possible storage errors, you can enclose the call in a try-catch block.

To retrieve the value of a key from either the session storage or the local storage, you call getItem with the key that you are interested in. The return will be a string value, which you can then use in your script:

string getItem(key)

Here key is the string key to retrieve the corresponding value.

To retrieve the value stored in the previous example, you would ask for the source key from the session storage by performing the following call:

textSource = sessionStorage.getItem('source');

Since the session and local storage are based around storage objects, you can also use object dot notation to access stored values of keys by using the key as the property name, as shown here:

textSource = sessionStorage.source;

Tip: In browsers such as Firefox, the user can disable storage. To validate that storage is available, your code should attempt to write and then retrieve a value. If the value cannot be retrieved, then storage may be disabled in the browser.

Now that we have briefly discussed the get and set methods of the session and local storage, we'll show a basic recipe in action. We will start the recipes with the session object and then move to local storage.

Beginner recipe: Getting and setting session storage

In this recipe, the HTML page will use the getItem and setItem methods of the sessionStorage object to store and retrieve the number of times that a visitor views a page in the session. This number is incremented with each refresh of the page and displayed to the visitor. Perform the following steps to create the page in Listing 1:

  1. Create a blank HTML page with a div titled divVisits.
  2. Add the init function in a set of script tags with the code from Listing 1.
  3. Add the window.addEventListener event handler to launch the init function after the page loads.

Listing 1: Displaying page visits using session storage

<!DOCTYPE html>   <html>   <head>   <meta charset="UTF-8" />   <title>11.1 Session Storage Page Visits</title>   <script>   function init() {        // reference the div for display     var divVisits = document.getElementById('divVisits');        // check if our browser supports sessionStorage     if (window.sessionStorage) {          var visits; // number of visits to this page          // check to see if our variable exists using dot notation       if (sessionStorage.visits) {            // retrieve key and convert to int         visits = parseInt(sessionStorage.getItem('visits'));            // increment the visits         visits++;          } else {         // default to first visit         visits = 1;       }          // update our visits variable       sessionStorage.setItem('visits',visits);          // display the number of session visits       divVisits.innerHTML = 'Session page visits: ' + visits;        } else {       // sessionStorage not available       divVisits = 'Window sessionStorage is not available';     }   }      // onload launch our init function   window.addEventListener('load',init,false);      </script>   </head>   <body>     <div id="divVisits"></div>   </body>   </html>

1 2 3 4 5 6 Page 2
Page 2 of 6
It’s time to break the ChatGPT habit
Shop Tech Products at Amazon