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..
Save data to localStorage:
<script> localStorage.setItem('firstname','Zakro'); </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.
The sessionStorage object is used much less often than localStorage.
The sessionStorage data works only within the current browser tab.
Save data to sessionStorage:
<script> sessionStorage.setItem('name', 'Zakro'); </script>
Read data from sessionStorage
<script> sessionStorage.getItem('name'); </script>