Unlike cookies, localStorage and sessionStorage are not sent to the server during each request. Many browers have at least 2 megabytes of data to store and configure them. The server cannot handle localStorage and sessionStorage via HTTP headers, everything via javascript.
Storage is associated with (domain / protocol / port triple), that is, different protocols or subdomains infer different storage objects, they can access data from each other.
Between localStorage and sessionStorage there are the same methods and properties:
setItem(key, value)
– save key / value pairsgetItem(key)
– get value by key.removeItem(key)
– remove the key / value pair.clear()
– delete everything.key(index)
– get the value of the corresponding keylength
– the length of stored items.
localStorage
Main features of localStorage
:
- All tabs and windows in the browser if the same source can share each other’s information.
- Data has no time to exist, it remains after brower restart or OS reboot.
For example, when you run this code:
localStorage.setItem('test', 1);
Then close / reopen the browser or open another window with the previous page, you can get the value you just set:
alert(localStorage.getItem('test')); // 1
They must share the same source (domain / protocol / port), the path may be different.
access localStorage
We can use the getting / setting key:
1 2 3 4 5 6 7 8 9 | // set key localStorage.test = 2; // get key alert( localStorage.test ); // 2 // remove key delete localStorage.test; |
This is allowed for historical reasons, and is mostly about the way things work, but is often not recommended, because:
- If the key is user-generated, it could be anything, like
length
ortoString
or anotherlocalStorage
integrationlocalStorage
. In that casegetItem/setItem
works fine, while faild whenlocalStorage
:123let key = 'length';localStorage[key] = 5; // Error, can't assign length - When there is a
storage
event
, it activates when we modify the data. Thatevent
does not occur with access tolocalStorage
. We will see that later in this section .
looping over keys
As we saw above, there are methods provided: get/set/remove
by key, but do they actually receive all stored values?
Unfortunately, the storage object cannot be repeated.
To get key / value pairs we need to loop them over an array:
1 2 3 4 5 | for(let i=0; i<localStorage.length; i++) { let key = localStorage.key(i); alert(`${key}: ${localStorage.getItem(key)}`); } |
String only
Key and value must be string.
sessionStorage
sessionStorage
is used less than localStorage
.
The properties and methods are the same, but it’s much more limited:
SessionStorage
only exists in the current browser tab.- Another tab with the same page will have different storage capacity.
- But it is shared between iframes in the same tab (assuming they come from the same origin).
- Data exists when the page refreshes, but takes time when closing / opening tabs.
Take a look:
sessionStorage.setItem('test', 1);
After refreshing the page, you can get back the data:
alert( sessionStorage.getItem('test') ); // after refresh: 1
Storage event
When data is updated to sessionStorage
or localStorage
, the storage
event
triggered with the property:
key
– changed (null
if.clear()
is called)oldValue
– old value (null
if new keys are added)newValue
– new value (null
if key removed)url
– the url of the document where the update occurred
It is important: the event triggers on all window objects where the store is accessible, except for the object that caused it.
Imagine, you have two windows with the same website so localStorage
is shared between them. You may want to open this page in two browser windows to check the code
below. If both windows are listening for the window.onStorage
event, each window will respond to updates that occurred in another window.
1 2 3 4 5 6 7 8 | // triggers on updates made to the same storage from other documents window.onstorage = event => { if (event.key != 'now') return; alert(event.key + ':' + event.newValue + " at " + event.url); }; localStorage.setItem('now', Date.now()); |
Thank you for reading. @@