JavaScript – How to Store Data in HTML5 Session Storage

HTML web storage provides us window.sessionStorage object for storing data on the client, which stores data for one session (i.e. data is lost when the browser tab is closed).

 

Here is the code how to store data in HTML5 session storage:

SessionStorageHelper.js
var SessionStorageHelper = (function() {

    _isSupported = function() {
        return (typeof(Storage) !== 'undefined');
    };
    
    // get saved data from sessionStorage
    get = function(key) {
    	var value = null;
    	
        if (_isSupported()) {
            var saved = sessionStorage[key];
            if (saved) {
                value = JSON.parse(saved);
            }
        }

        return value;
    };

    // save data to sessionStorage
    save = function(key, value) {
        if (_isSupported()) {
            value = JSON.stringify(value);
            try {
                sessionStorage.setItem(key, value);
            } catch (error) {
                console.log(error);
            }
        }
    };

    // remove saved data from sessionStorage
    remove = function(key) {
        if (_isSupported()) {
            sessionStorage.removeItem(key);
        }
    };

    // remove all saved data from sessionStorage
    clear = function() {
        if (_isSupported()) {
            sessionStorage.clear();
        }
    };

    return {
        get: get,
        save: save,
        remove: remove,
        clear: clear
    };
  
})();

In the above code, we implement SessionStorageHelper containing the following methods:

  • get: the public method for getting data from sessionStorage
  • save: the public method for saving data to sessionStorage
  • remove: the public method for removing data from sessionStorage
  • clear: the public method for removing all data from sessionStorage
  • _isSupported: the private method for checking whether HTML 5 Session Storage is supported or not

 

Use the function:

// save data to sessionStorage
SessionStoreageHelper.save('mydog', 'Bob');

// get saved data from sessionStorage
var name = SessionStoreageHelper.get('mydog');

// remove saved data from sessionStorage
SessionStoreageHelper.remove('mydog');

// remove all saved data from sessionStorage
SessionStoreageHelper.clear();
0 0 vote
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x