Basic Difference Between Local Storage and Session Storage in HTML 5
Table of contents
This article explains what is the basic difference between HTML 5 local storage and session storage. Basically, both session storage and local storage are part of storage mechanism which is introduced with HTML5. By using these two, we can store information on client side itself. I hope you will like it.
If you are new to the term local storage, I recommend you to read my article here: Local Storage
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 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
Using the code
Here in my application, I have added two HTML5 pages.
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.
<!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>
<!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.
Figure: Local Storage
Figure: 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.
Figure: Local storage
Figure: Session storage
Please note that session storage is null. You can see the session storage only if you set it on that running page.
Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.
Your turn. What do you think?
A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.