Do you want to use session in JavaScript?
In this tutorial, I am going to show you how you can do that.
You can use LocalStorage or sessionStorage for maintaining the sessions in JavaScript.
As you know that JavaScript is a client side scripting language, so this session will be stored in the browser.
In the case of sessionStorage, the data is stored only until the window or tab is closed,
while with localStorage, the data is stored until the user manually clears the browser cache.
data survives a page refresh (for sessionStorage)
data survives even a full browser restart (for localStorage).
We already have cookies. Why additional objects?
Unlike cookies, web storage objects are not sent to the server with each request.
Both storage objects provide same methods and properties:
setItem(key, value) – store key/value pair. getItem(key) – get the value by key. removeItem(key) – remove the key with its value. clear() – delete everything. key(index) – get the key on a given position. length – the number of stored items.
localStorage
localStorage is generally used for session storage in JavaScript.
localStorage example
Save data to localStorage:
<script> localStorage.setItem('firstname','Vikash'); </script>
Read data from localStorage:
<script> alert(localStorage.getItem('firstname')); </script>
We only have to be on the same origin (domain/port/protocol), the url path can be different.
The localStorage data is shared between all windows with the same origin.
sessionStorage
The sessionStorage object is used much less often than localStorage.
The sessionStorage data works only within the current browser tab.
sessionStorage example
Save data to sessionStorage:
<script> sessionStorage.setItem('name', 'Vikash'); </script>
Read data from sessionStorage
<script> sessionStorage.getItem('name'); </script>
Hope you have understood how to use session in JavaScript. If you have any query regarding this topic, feel free to comment.