Skip to Content

HTML5. It’s a mercy!

JavaScript developers can use the new Session and Local Storage API to save data in certain scopes. As a result, it’s possible to create a real session context in your web application analog to server-side solutions. In this post i want to show you, how you can use advanced JavaScript desing pattern to create a custom SessionManager API for your web-project. You can download the complete source-code of the example at github. Besides, you can check out the live-demo right here: live-demo

1. Requirements

At first, we have to determine some requirements for the SessionManager.

  • It’s important to create a JavaScript API, which runs in its own namespace, so we don’t have risky side effects to other libraries.
  • We want to store real JavaScript objects, so the SessionManager has to do the complete serialization and deserialization.
  • We want to store our objects in HTML5 Session Storage, so the lifetime of our data are conscious limited. Moreover, we have to store our data in key-value pairs, which means, that we have to save our object as a JSON-String.

SessionStorage.jpg

2. Distinction

For this simple example, we don’t want to create a generic API, which is able to cast to the correct object-type. We will implement specific functions.

3. The Coding

As you can see in the live-demo, i used the very popular web front-end framework Twitter Bootstrap as a template for the html-sites (sry, but for such a tutorial i can’t use SAPUI5). In this example, I don’t use any JavaScript-Componets from Bootstrap, so everything what you see in the following listings is pure JavaScript and jQuery code (so usable in a SAPUI5 app).

3.1 main.js

The first js-file called “main.js” represents the interface to HTML templates. These functions are called from input.html and result.html and consist of DOM-operations and function calls to other JavaScript files.

(function(MYSAP, $, undefined) {
          MYSAP.submitPerson = function(){
                    // Read data from DOM
                    var firstName = $('#input_firstname').val();
                    var lastName  = $('#input_lastname').val();
                    var age                = $('#input_age').val();
                    // Create new object
                    var person = new MYSAP.Person(firstName, lastName, age);
                    // Call instance method
                    person.log();
                    // Write to SessionStorage
                    MYSAP.SessionManager.setPerson('person', person);
          };
          MYSAP.readPerson = function(){
                    // Read person from SessionStorage
                    var person = MYSAP.SessionManager.getPerson('person');
                    // If person is not null...
                    if(person){
                              // Call instance method
                              person.log();
                              // Write data to DOM
                              $('#input_firstname').html(person.firstName);
                              $('#input_lastname').html(person.lastName);
                              $('#input_age').html(person.age);
                    }else{
                              // Show warning
                              $('.alert-block').show();
                    }
          }
          MYSAP.clearPerson = function(){
                    // Clear person from SessionStorage
                    MYSAP.SessionManager.clearPerson();
                    // Reload current location
                    location.reload();
          }
}(window.MYSAP = window.MYSAP || {}, jQuery));

3.2 person.js

In person.js i defined a simple model with a function constructor and an exemplary instance method. An object of this prototype represents our session object, which will be stored in HTML5 Session Storage.

(function(MYSAP, $, undefined) {
          // Constructor
          MYSAP.Person = function(firstName, lastName, age){
                    this.firstName = firstName;
                    this.lastName  = lastName;
                    this.age             = age;
          };
          MYSAP.Person.constructor = MYSAP.Person;
          // Sample instance method
          MYSAP.Person.prototype.log = function(){
                    console.log(this.firstName + ' ' + this.lastName + ', ' + this.age + ' years');
          };
}(window.MYSAP = window.MYSAP || {}, jQuery));

3.3 sessionmanager.js

In sessionmanager.js you can see the logic for accessing Session Storage and serialization/deserialization.

( function(MYSAP, $, undefined) {
          MYSAP.SessionManager = function() {};
          MYSAP.SessionManager.getPerson = function(key) {
                    var person;
                    // Get item over SessionStorage API
                    var person_storage = sessionStorage.getItem(key);
                    if (person_storage) {
                              // Parse JSON to object
                              person_storage = JSON.parse(person_storage);
                              // Create new object
                              person = new MYSAP.Person(person_storage.firstName, person_storage.lastName, person_storage.age);
                    }
                    return person;
          };
          MYSAP.SessionManager.setPerson = function(key, person) {
                    if (person) {
                              // Serialize Object to JSON
                              var person_storage = JSON.stringify(person);
                              // Set item over SessionStorage API
                              sessionStorage.setItem(key, person_storage);
                    }
          };
          MYSAP.SessionManager.clearPerson = function() {
                    sessionStorage.removeItem('person');
          }
}(window.MYSAP = window.MYSAP || {}, jQuery));

4. The App

If you submit the first form, all data will be stored into Session Storage. On the next site, data will be read from Session Storage and displayed. When you now switch between both sites, you will see that the result.html will always show the saved data, as long as you don’t close your browser or tab.

I wanted to show you with this post, how simple it is to create a web-application with client-side session context. You always will need a session handling concept like this, if you don’t create a single-page app.

And now, please enjoy!

To report this post you need to login first.

4 Comments

You must be Logged on to comment or reply to a post.

    1. Ajain Vivek

      Nice Post Micheal 🙂

      Session storage holds the information or data on single tab or window keeping client end security in mind. Storing the data on single tab or window sometimes doesn’t help in SSO applications and also lead to leakage of data while the user has logged out of application from another tab.

      (0) 
      1. Michael Herzog Post author

        Hi Ajain,

        right, it’s good that you call attention to these points. The restrictions with SSO and multiple tabs were not subjects of this post, but it’s still important to know.

        Regards

        (0) 

Leave a Reply