JavaScript localStorage: The complete guide
javascript localStorage the complete guide

JavaScript localStorage: The complete guide

Dead Simple Chat Team

Table of Contents

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

đź’ˇ
New to DeadSimpleChat? It's a turn key chat that you can easily add to your website or App —without any complicated code. For Virtual / Live events, SaaS App, Social Platform, Education, Gaming, Finance  Sign Up for Free

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

  1. sessionStorage
  2. localStorage
Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

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:

  1. setItem
  2. getItem
  3. removeItem
  4. clear
  5. key
Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

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 the sessionStorage 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 the localStorage 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

Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

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.

window.localStorage.setItem('candy name', 'Mars Bar');
setItem()

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

getting and setting localStorage

There are multiple ways of storing the data in the localStorage using setItem. You can access data in the Object like way:

window.localStorage.candyName = 'Mars';
window.localStorage['candyName'] = 'Mars';
window.localStorage.setItem('candyName','mars');
multiple ways of storing data in localStorage

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

using Object 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

const getCandy = window.localStorage.getItem('candy name');
getItem()

This would return the value as Mars Bar

get and set items

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'
Object notation

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

window.localStorage.removeItem('candies');
removeItem from 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

remove Item

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

window.localStorage.clear();
clear the local storage

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

local storage clear

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

window.localStorage.key(index);
key method of the localStorage

let us use the console to see how the key works.

We have put 2 key/value pairs in the localStorage like

window.localStorage.candyName = 'Mars'
window.localStorage['candy2'] = 'turtles'
adding 2 key/value pairs in localStorage

let us use the length to check for the contents of the localStorage

window.localStorage.length
using the length property
using the length property

as you know the index starts from 0. let us see what is at index 0

localStorage.key(0)

and let us see what is at index 1

localstorage.key(1)

Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

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

window.localStorage.length
length property of 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
length property

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

length on empty localStorage

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

Storage Event

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

Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

LocalStorage: Interesting facts

Here are some of the interesting facts about the localStorage

  1. localStorage is always stored in UTF-16 string format. Integer keys are converted into string and stored in the localStorage
  2. localStorage data is specific to the protocol of the browser and website. For example it is different in http and https
  3. for documents loaded from file the requirements for localstorage is undefined and is different for different browsers
  4. localStorage for incognito or private browsers is deleted when the browser is closed
Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat

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: or data: schemes. Many modern browsers treat file: 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

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

Chat API Trusted by world’s biggest corporations | DeadSimpleChat
Chat API and SDk that supports 10 Million Concurrent Users. Features like Pre-Built turn key Chat Solution, Chat API’s, Customization, Moderation, Q&A, Language Translation.
DeadSimpleChat