Introduction
HI. This article explains what the basic difference of HTML 5 local storage and session storage is in a practical way. I hope you will like it.
If you are new to the term local storage, I recommend you to read my article here.
Basic scenario where you can use
- If you need to carry a value throughout your application or throughout your pages, you can use local storage. For example, we can store a logged-in username in local storage that we may need to access in all the pages. I strongly recommend to not store any secured data (for example a “password”) in local storage.
- In some scenario, we may need to set a key element depending on the pages we have in the application. For example, if we need to store the page name (any key element that may be different).
So let's start
Here in my application I have added two HTML5 pages.
- HtmlPage1.html
- HtmlPage2.html
In HtmlPage1.html I have set local storage and session storage, now I am trying to access that in HtmlPage2.html. Please see the following source.
HtmlPage1.html
- <!DOCTYPE html>
- <html
- xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>Difference between local storage and session storage</title>
- <script>
- localStorage.setItem("myKey", 1);
- sessionStorage.setItem("myKey", 1);
- var myVal = localStorage.getItem("myKey");
- alert("My local storage value is : " + myVal);
- alert("My session storage value is : " + sessionStorage.getItem("myKey"));
- </script>
- </head>
- <body>
-
- </body>
- </html>
HtmlPage2.html
- <!DOCTYPE html>
- <html
- xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>Difference between local storage and session storage</title>
- <script>
- var myVal = localStorage.getItem("myKey");
- alert("My local storage value is : " + myVal);
- alert("My session storage value is : " + sessionStorage.getItem("myKey"));
- </script>
- </head>
- <body>
-
- </body>
- </html>
When you run the first page, in the browser console you will see as in the following image.
Local Storage
Session Storage
Now it is time to run the second page.
Once you run that please check in the console. You can see as follows.
Local storage
Session storage
Please note that session storage is null. You can see the session storage only if you set it in that running page. I hope you like it.
Conclusion
Adding points as suggested by Afzaal Ahmed Zeeshan.
Session storage stays active until the session stays; browser is active, user is working etc. Once the session is cleared they are cleared
Please provide your valuable suggestions and comments. Thanks in advance.
Kindest Regards,
Sibeesh Venu