LocalStorage and SessionStorage

LocalStorage and SessionStorage are two different mechanisms that are both part of modern web browsers. Through these, you can easily store key/value pairs in the user's web browser storage space. That space is limited in size, but you can normally store around 10 MB on desktops and around 5 MB on mobile devices; this will be more than enough for our small application.

The storage space is user-configurable and can also be 0 if the browser is in private or incognito mode.

LocalStorage and SessionStorage both expose the same APIs and capabilities, but differ in persistence. While LocalStorage survives page reloads, SessionStorage does not. Also, each browser session has a separate SessionStorage instance: if the browser tab or window is closed, then the data will be lost.

The data that you store is only accessible to the document origin, which is determined by the combination of a domain, subdomain, and port. This means that a web application hosted at a different origin should not be able to access the data.

Both of these APIs are very useful for storing non-sensitive data, but they should never be used to store confidential information since they were not designed for that. Any JavaScript code executing on your page has full access to the storage space. Additionally, because the data is stored on the client's computer, it is at risk from that fact alone. You can learn more about the security of these APIs here: https://www.rdegges.com/2018/please-stop-using-local-storage.

The API is very simple to use:

// persisting: 
let key = 'Foo'; 
localStorage.setItem(key, 'Bar'); 
 
// retrieving 
let value = localStorage.getItem(key); 
 
// updating 
localStorage.setItem(key, 'Bar2'); 
 
// removing 
localStorage.removeItem(key); 
 
// removing everything 
localStorage.clear(); 

As you can see, the API is synchronous. The same is true for sessionStorage.

One drawback of these two APIs is that they can only store string values. This means that, if you have another type of data, then you need to convert them back and forth, for example, using JSON.stringify(data) and JSON.parse(jsonData).

Before using these APIs, you need to make sure that they are actually available, using a check such as if(!window.localStorage) { ...​ } or if(!window.sessionStorage) { ...​ }.

You can find everything there is to know about these APIs here:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.70.93