Dead Simple Chat offers prebuilt Chat that can be added in minutes to any app or website. Can be completely customized and offers powerful API and SDK.
Introduction
JavaScript localStorage
is basically storage that is in the browsers Window
Object. You can store anything in the localStorage
and it will be persistent through page loads and even if the browser closes and reopens
localStorage
and its related sessionStorage
are part of the Web Storage API. We will be learning more about these below
What is Web Storage API?
Web Storage API provides methods through which browsers can store key/value pairs of data (like Objects).
The key/value pairs stored in the web storage API are always in the form of strings. (integer keys are automatically converted to strings)
There are a set of methods provided by the Web Storage API that you can use to access, delete modify the key/Value pairs
There are two types of storage available in the Web Storage API
sessionStorage
localStorage
What is LocalStorage?
LocalStrorage
is part of the Web Storage API. It allows you to store persistent data (data remains on browser reloads and when the browser is closed and reopened) in the browser Window
Object as key/value pairs of strings.
There are five methods of localStorage and these are:
- setItem
- getItem
- removeItem
- clear
- key
Difference between sessionStorage and localStorage
Both sessionStorage
and localStorage
are part of the web storage api.
- The
sessionStorage
is only available till the browser is open, when the browser is closed thesessionStorage
is deleted. (`sessionStorage` is available when the browser reloads but when the browser is closed sessionStorage is deleted) - The
localStorage
is the persistant data even when the browser is closed thelocalStorage
data remains in the browser localStorage
can be deleted manually by the user and it is automatically deleted when the user is in incognito window or private window and the user closes the browser
Both sessionStorage
and localStorage
provides similar methods to access and store data in the browser
We will be learning more about the LocalStorage
methods below
LocalStorage Methods
There are five methods in the localStorage
. These methods let you store items, get Items, remove Items and clear the localStorage
.
1. setItem(): Store data in the localStorage
Using localStorage.setItem API you can store key/value pairs in the local storage. here is an example on how you can store the data.
the candy name
is the key and the Mars Bar
is the value. As we have mentioned localStorage only stores strings.
You can try this in the browser itself. Here is an example to storing the data in the chrome browser
There are multiple ways of storing the data in the localStorage
using setItem
. You can access data in the Object like way:
It is allowed but not recommended to store or access data in the object like way because the user generated key can by anything like toString
or length
or any other built in method name of the localStorage
In which case the getItem
and setItem
would work fine but the Object like method would fail
using Object like notation
2. getItem(): Retrive data from the localStorage
Using the getItem API we can retrive the key/value pairs stored in the localStorage
getItem() accepts a key and returns the value as a string
This would return the value as Mars Bar
using Object Notation
Using Object notation you can also access the data (although it is not recommended)
window.localStorage.candyName
returns 'Mars'
window.localStorage['candy2']
returns 'turtles'
3. removeItem() remove an item from the localStorage
you can remove any item from the localStorage
using the removeItem
method
Pass the key of the item that you need to remove to the removeItem
method and it is deleted from the localStorage
let's use the console to see how the removeItem works. First we will use the length property to check how many items are in teh local storage
As you can see when we use the length property it shows there are 2 items in the localStorage
. After we remove an item now there is only one item remaining in the local storage
4. clear() clear the localStorage
With Clear() method of the localStorage api you can clear the entire localStorage and delete all the data in the localStorage
let us use the console to see how the clear method of the localStorage
works
We will use the length to check for the number of items in the localStorage
As you can see there are 2 items stored in the localStorage
and we used the clear method now there are 0 items stored in the localStorage
5. key() returns the n th  key in the storage
the key method can be passed any integer and it will return the key stored at the nth key in the storage Object
let us use the console to see how the key works.
We have put 2 key/value pairs in the localStorage like
let us use the length
to check for the contents of the localStorage
as you know the index starts from 0. let us see what is at index 0
and let us see what is at index 1
Storage Property
length : number of key/value pairs stored in the local
The length is a read-only property of the localStorage
interface. It returns the number of key/value pairs stored in the localStorage
We can use length property to test whether the localStorage
is populated or not.
Uptill now we have used the length property multiple times and you might have become familier with.
Let us use the length property in different use cases to futher explore its uses. Let us open the console and see how we can use the length property
window.localStorage.length
2
now the length property can also be used to check if the localStorage is empty. Let us clear the localStorage
and see what happens if we use the length property
It returns 0. hence we know if the length property returns 0 then the localStorage is empty
Storage Event
The Storage event is fired whenever a change is made to the storage object.
StorageEvent is sent to the window when a storage area the window has access to is changed within the context of another document
Storage event are events that are fired whenever a change takes place and you can listen to the storage event and make appropriate decision in your website or application.
Constructor
StorageEvent()
Returns a new StorageEvent
Object
let us use the console to create a new instance of the storageEvent()
creating a new instance of the StorageEvent
new window.StorageEvent(keys)
returns
Instance Properties
Keys (read only)
Returns a String that represents the key that has been changed. The key attribute is null when the change is caused by the clear() method
newValue(read only)
Returns a String with the new value of the key that has been changed. It is null when clear() method has been used or the key has been removed
oldValue(read only)
Returns a String with the original value of the key. It is null when a new key has been added where there was no key before
storageArea(read only)
Returns a storage Object that represents the storage area that was affected.
url(read only)
Returns a string with the url of the document who key is changed
LocalStorage: Interesting facts
Here are some of the interesting facts about the localStorage
localStorage
is always stored in UTF-16 string format. Integer keys are converted into string and stored in the localStoragelocalStorage
data is specific to the protocol of the browser and website. For example it is different in http and https- for documents loaded from
file
the requirements for localstorage is undefined and is different for different browsers localStorage
for incognito or private browsers is deleted when the browser is closed
LocalStorage Limitations
Here are some of the limitations for localStorage
- Limited upto 5MB of data
- do not store sensitive data in
localStorage
as it can be easily accessed by  cross site scripting localStorage
is syncronous meaning it is accessed one after the other and- do not use
localStorage
as a database
Detecting localStorage: testing for availability
This functionality is available in all the newer browser you need to test it if you are supporting very very old browsers like Internet Explorer 6 or 7 or in some limited circumstances
Browser Compatibility
LocalStorage is compatiable with all the latest browsers. Only the very very old browsers like Internet Explorer 6 or 7 do not support localStorage
In some situations like the user is in private window or the user is in incognito window the data would be immediately deleted when the user closes the window
The user can also disable localStorage
Exceptions
securityError
A security error is thrown in the following cases:
- Origin is not a valid scheme/host/port tuple error. This happens when the origin uses
file:
ordata:
schemes. Many modern browsers treatfile:
origin as opaque origin. What this means is that the file or files that come from the same folder are assumed to come from different sources and could trigger CORS error - The request violates a policy decision. For example the user has disabled the use of localStorage on the browser
Here are some of the relevant articles
- Axios GET and POST examples
- Data Fetching with getServerSideProps and getStaticProps
- How to safely use dangerouslySetInnerHTML in React
- Environment Variables in NodeJs: The complete Guide
Conclusion
In this article I have explained the localStorage
and its methods and how you can use localStorage
to save data and access it, deleted it and modify it