How To Use Html5 Session Storage & Local Storage With JavaScript Example

This article will tell you how to use html5 sessionStorage object to manage string text in the session scope, it will also tell you how to use html5 localStorage object to manage string text in the web browser permanently.

1. How To Use sessionStorage Variable In Html5.

  1. The sessionStorage object can be used to save or load string text in the web browser per session.
  2. When you open a new browser tab or a new web browser or restart the web browser, the data that is saved in the sessionStorage object will be lost.
  3. The sessionStorage object’s method setItem(key, value) can be used to save data in the sessionStorage object.
  4. The sessionStorage object’s method getItem(key) can be used to get data by key in the sessionStorage object.
  5. You can use the sessionStorage object’s length attribute to get the item number saved in the sessionStorage object.
  6. The sessionStorage object’s key(index) method can get the key data by the index number.

2. How To Use localStorage Variable In Html5.

  1. The localStorage variable is similar to the sessionStorage variable, they have the same methods and properties.
  2. The only difference is that the localStorage object will save data per web browser, the data saved in it will not be lost when you restart the web browser, open a new web browser or open a new tab.
  3. But the different web browser providers ( Google Chrome, Firefox ) will not use the same localStorage object, so the data you saved in Google Chrome can not be read in Firefox.

3. Html5 sessionStorage VS localStorage Examples.

  1. The demo video URL is https://youtu.be/CJbEC3cpaAk.
  2. There are 2 apps in this example.
  3. The above app shows the difference between sessionStorage and localStorage variable object.
  4. The below app shows th
  5. There are 2 source files in this example, html5-local-session-storage-example.html, html5-local-session-storage-example.js.
  6. html5-local-session-storage-example.html.
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Html5 Local Storage Vs Session Storage With Example</title>
    <script type="text/javascript" src="html5-local-session-storage-example.js" charset="utf-8"></script>
    <style>
    canvas{
      display:inline-block;
      margin-top:10px;
    }
    </style>
    </head>
    <body>
    <h3>Html5 Local Storage Vs Session Storage With Example.</h3>
    <div style="display:block; margin-top: 10px;">
        <label>
            Input the text to save:
        </label>
        <input type="text" id="inputText" value="This is the text to save." />
        <div style="display:block; margin-top: 10px;">
            <input type="button" id="saveToLocalBtn" value="Save To Local" onclick="saveToLocal('inputText')" />
            <input type="button" id="saveToSessionBtn" value="Save To Session" onclick="saveToSession('inputText')" />
            <input type="button" id="loadFromLocalBtn" value="Load From Local" onclick="loadFromLocal('outputText')" />
            <input type="button" id="loadFromSessionBtn" value="Load From Session" onclick="loadFromSession('outputText')" />
        </div>
        <output id="outputText" style="display:block"></output>
    </div>
    <div style="display:block; margin-top: 10px;">
        <label style="display:block; margin-top: 10px;">
            Simple Notes Recorder:
        </label>
        <textarea id="noteTextArea" rows="10" cols="60" style="display:block; margin-top: 10px;"></textarea>
        <div style="display:block; margin-top: 10px;">
            <input type="button" id="saveNoteBtn" value="Save A Note" onclick="saveNote('noteTextArea')" />
            <input type="button" id="clearAllNotesBtn" value="Clear All Notes" onclick="clearAllNotes()" />
        </div>
        <output id="outputNotesList" style="display:block;margin-top: 10px;"></output>
    </div>
    </body>
    </html>
  7. html5-local-session-storage-example.js.
    var KEY_INPUT_TEXT = "KEY_INPUT_TEXT";
    
    var ID_OUTPUT_NOTES_LIST = "outputNotesList";
    
    function saveToLocal(inputTextId){
    
        inputText = document.getElementById(inputTextId);
        
        if(inputText==null){
            alert('Can not find the Html input text element with the id ' + inputTextId);
            return;
        }
    
        if(inputText.value.trim()==''){
            alert('Please input some text to save.');
            return;
        }
    
        localStorage.setItem(KEY_INPUT_TEXT, inputText.value);
    
        alert('Save input text to local storage successfully.');
    
    }
    
    function saveToSession(inputTextId){
    
        inputText = document.getElementById(inputTextId);
        
        if(inputText==null){
            alert('Can not find the Html input text element with the id ' + inputTextId);
            return;
        }
    
        if(inputText.value.trim()==''){
            alert('Please input some text to save.');
            return;
        }
    
        sessionStorage.setItem(KEY_INPUT_TEXT, inputText.value);
    
        alert('Save input text to session storage successfully.');
        
    }
    
    
    function loadFromLocal(outputTextId){
    
        outputText = document.getElementById(outputTextId);
        
        if(outputText==null){
            alert('Can not find the Html output element with the id ' + outputTextId);
            return;
        }
    
        savedText = 'Text saved in local storage: ' + localStorage.getItem(KEY_INPUT_TEXT);
    
        outputText.value = savedText;
    
    }
    
    function loadFromSession(outputTextId){
    
        outputText = document.getElementById(outputTextId);
        
        if(outputText==null){
            alert('Can not find the Html output element with the id ' + outputTextId);
            return;
        }
    
        savedText = 'Text saved in session storage: ' + sessionStorage.getItem(KEY_INPUT_TEXT);
    
        var len = sessionStorage.length;
        for(var i=0;i<len;i++){
    
            key = sessionStorage.key(i);
            value = sessionStorage.getItem(key);
    
            console.log('Key = ' + key);
            console.log('Value = ' + value);
    
        }
    
        outputText.value = savedText;
    
    }
    
    function saveNote(noteTextAreaId){
    
        var noteTextAreaObject = document.getElementById(noteTextAreaId);
    
        if(noteTextAreaObject==null){
    
            alert('Can not find the note text area object with id ' + noteTextAreaId);
            return;
    
        }else if(noteTextAreaObject.value.trim() == ''){
            alert('You must input something in our note before save it.');
            return;
        }
    
    
        var currDate = new Date();
    
        var currTime = currDate.getTime();
    
        localStorage.setItem(currTime, noteTextAreaObject.value);
    
        alert('The note has been saved, it will be shown below.');
    
        showNotes();
    }
    
    
    
    function showNotes(){
    
        var notesListObject = document.getElementById(ID_OUTPUT_NOTES_LIST);
    
        if(notesListObject==null){
    
            alert('Can not find the note list output html element with the id ' + ID_OUTPUT_NOTES_LIST);
            return;
    
        }
    
        var noteListString = '';
    
        var notesListLength = localStorage.length;
    
        for(var i=0; i<notesListLength; i++){
    
            var key = localStorage.key(i);
    
            var noteData = localStorage.getItem(key);
    
            var notePubDate = new Date();
            notePubDate.setTime(key);
    
            var year = notePubDate.getFullYear();
            var month = notePubDate.getMonth();
            var day = notePubDate.getDate();
    
            var hour = notePubDate.getHours();
            var minute = notePubDate.getMinutes();
            var seconds = notePubDate.getSeconds();
    
            notePubDateString = hour + ':' + minute + ':' + seconds + ' ' + ( month + 1 ) + '/' + day + '/' + year;
    
            noteListString += notePubDateString;
            noteListString += ' : '
            noteListString += noteData;
            noteListString += '<hr>'
        }
    
        notesListObject.innerHTML = noteListString;
    }
    
    
    function clearAllNotes(){
    
        localStorage.clear();
    
        showNotes();
    
    }
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Clicky
0
Would love your thoughts, please comment.x
()
x