JavaScript – How to Store Data in HTML5 Local Storage

HTML web storage provides us window.localStorage object for storing data on the client, which stores data with no expiration date.

 

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

LocalStorageHelper.js
var LocalStorageHelper = (function() {

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

        return value;
    };

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

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

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

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

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

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

 

Use the function:

// save data to localStorage
LocalStorageHelper.save('myname', 'Kai');

// get saved data from localStorage
var name = LocalStorageHelper.get('myname');

// remove saved data from localStorage
LocalStorageHelper.remove('myname');

// remove all saved data from localStorage
LocalStorageHelper.clear();
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x