14-day Cloud trial
Start today. For free.

One editor. 50+ features. Zero constraints. After your trial, retain the advanced features.

Try Professional Plan for FREE
PricingContact Us
Log InGet Started

JavaScript and localStorage in a nutshell

June 1st, 2023

6 min read

Written by

Ben Long

Category

How-to Use TinyMCE

It’s unavoidable that hosting your app needs a cloud service provider and a database. But sometimes, you need to get something done in HTML without the added database or cloud service provider. In this case, you can use JavaScript to access localStorage. But you no doubt have questions: what is localStorage, when can you use it, and is it secure?

If you already know what you’re getting yourself into, check through the table of contents, and start with the demo of using JavaScript localStorage with a rich text editor. Otherwise, this article provides an introduction to JavaScript localStorage.

Contents

What is localStorage in JavaScript
    Advantages and limitations of localStorage
        localStorage vs sessionStorage vs Cookie
        SessionStorage vs localStorage
        localStorage vs Cookie
        IndexedDB vs localStorage
How to use localStorage methods in JavaScript
How to clear localStorage
localStorage JavaScript example
localStorage next steps

What is localStorage in JavaScript

localStorage in JavaScript allows web applications to store data locally within the user's browser – with no expiration date. The data isn’t deleted when the browser is closed, and is available when the browser is opened again. 

localStorage also allows your customers to access specific data quickly without the overhead of a database. There are other advantages and disadvantages to understand when working with localStorage.

Advantages and disadvantages limitations of JavaScript localStorage

Advantages

  • It stores up to 5-10MB of data (depending on the browser).
  • Easy to use – no need for a web server or backend database.
  • Great for getting an idea up and running and for testing purposes.

Limitations

  • It only stores up to 10MB of data (5MB in some browsers).
  • It can only store strings. This can restrict you from using it for more complex scenarios although, HTML can be stored as a string – more on that later...
  • It’s local to the browser and specific to the origin (per domain and protocol), and there’s no guarantee that the data will persist even in that same context.

Security limitation

  • It’s not secure. Don’t store any private or personal information in localStorage.

localStorage vs sessionStorage vs cookie

The main difference between localStorage, sessionStorage, and cookie storage is size. 

There’s:

  • 10MB available for localStorage
  • 5MB for sessionStorage 
  • 4KB for Cookies. 

Of these three types of storage, localStorage is the newest kind of in-browser storage

Unlike sessionStorage, data stored in localStorage persists, and is accessible even after the browser closes. On Stack Overflow, cssyphus put together a useful explanation that contrasts the different storage types along with a list of resources.

SessionStorage is useful when you need browser storage that does not impact web application performance. Login credentials are held in sessionStorage as they are cleared once the open tab closes. 

Cookies are the oldest kind of in-browser storage. With their small capacity, they can hold small amounts of data, and are not designed to hold sensitive data such as login credentials.

Sessionstorage vs localStorage

Together, these two kinds of storage are the main data storage objects available that the browser can access easily for storing and retrieving information for customers. The main difference between Session and Local kinds of storage is the lifespan of the stored data. 

SessionStorage is tied to a specific tab the browser may have open, whereas localStorage is accessible across any tab the browser has open. Once the tab closes, the sessionStorage is deleted, but localStorage persists.

localStorage vs cookie

Compared to localStorage, Cookies are older, and can only fit small amounts of data. There are two kinds of Cookies: session, and persistent. 

  • Session Cookies, like sessionStorage, expire when the browser closes. 
  • A persistent Cookie has an expiry attribute, or a max-age attribute that designates when the browser deletes the data held in cookie storage. 

Cookies are accessible by servers, as when browsers interact with a server, cookie data is sent along with requests and responses.

IndexedDB vs local storage

A new kind of browser storage, IndexedDB appeared in an attempt to make an improved version of localStorage. Contrasting the two, IndexedDB has a more complex API syntax compared to localStorage. IndexedDB allows for the storage of structured data. 

Unlike localStorage, IndexedDB is described as a JavaScript-based object-oriented database. Its design is to provide database-like behavior without the need for an internet connection to a web-server.

How to use localStorage methods in JavaScript

There are four basic JavaScript localStorage methods you can use to access and work with localStorage:

  • setItem() - takes a key-value pair and adds it to localStorage
  • getItem() - takes a key and returns the corresponding value
  • removeItem() - takes a key and removes the corresponding key-value pair
  • clear() - clears localStorage (for the domain)

To test out these methods, the following procedure uses the setItem() and getItem() methods. Feel free to try out the other methods in a similar way.

  1. Open a browser, and then access the console. For example, in Google Chrome, open Developer Tools and click on the Console tab.

  2. Enter the localStorage command, and the current stored data will be returned. For example (assuming it’s empty to begin with):

localStorage

Storage {length: 0}
  1. Enter localStorage.setItem('myKey', 'testValue') and the string testValue will be stored against the key myKey:

localStorage.setItem("myKey", "testValue");
undefined;
localStorage
Storage {myKey: "testValue", length: 1}

NOTE: undefined just means that no value is returned from that method. Enter localStorage again to view the stored data.

  1. Enter localStorage.getItem('myKey') and the corresponding string will be returned:

localStorage.getItem("myKey");

("testValue");

TIP: Type localStorage. (with the ‘.’) into the console and a full list of relevant methods will appear.

How to clear localStorage

You can run the command clear() to completely clear the localStorage data (for the domain):

  1. Check if there is content stored in localStorage:

localStorage

Storage {length: 0}
  1. For the purpose of the test, add some content to clear:

localStorage.setItem("clearKey", "clearThisValue");

undefined;
  1. Clear the localStorage data using the clear() method:

localStorage.clear();

undefined;
  1. Check again to confirm the local storage is clear.

localStorage

Storage {length: 0}

localStorage JavaScript example

The following demo shows how you can store information from the TinyMCE text area in localStorage:

  1. Create a simple index.html file with a single textarea, and two buttons as follows. The textarea id can be anything – in this example, we’ve called it myTextArea.

<!DOCTYPE html>
<html lang="en">
 <head>
 </head>
 <body>
   <h1>JavaScript localStorage demo</h1>
   <textarea id="myTextarea" rows="10" cols="80"></textarea>
   <p></p>
   <button onclick="mySave()">Save</button>
   <button onclick="myLoad()">Load</button>
   <script>

     function mySave() {
       var myContent = document.getElementById("myTextarea").value;
       localStorage.setItem("myContent", myContent);
     }

     function myLoad() {
       var myContent = localStorage.getItem("myContent");
       document.getElementById("myTextarea").value = myContent;
     }
   </script>
 </body>
</html>

The demo content has two JavaScript functions: mySave() and myLoad(). The buttons are configured so that when clicked they trigger the relevant JavaScript function. Here’s how it works in more detail:

  • document.getElementById() gets and sets the value of the element specified. In this case, it’s accessing the textarea with id myTextArea.
  • The mySave() function accesses the current value of the textarea and assigns it to a variable myContent.
  • This variable is then used as the value associated with key myContent in localStorage.
  • The myLoad() function operates in a similar way, only in reverse.

Open the demo HTML file in a browser. What it looks like on your screen will depend on your CSS. The following image shows a demo with some custom CSS for the buttons to make it more visually more interesting than the default:

JavaScript localStorage example running in a browser.

 

Get Your Free TinyMCE API Key →

 

  1. Type something in the textarea and click Save. (For example, the demo contains a snippet of prose from Frankenstein) The content then saves to localStorage.
  2. Refresh the page, and the content will disappear.
  3. Click the Load button, and the content is retrieved from localStorage, and appears in the text area.

TIP: While you’re on the page, you could try opening the browser console from within Developer Tools and executing some of the localStorage methods as shown in the previous section to confirm what’s happening behind the scenes.

localStorage next steps

Why not try taking this example one step further? Check out the article with more information on adding a rich text editor that works with JavaScript localStorage:

JavaScript localStorage example with rich text editor.

If you’d like to know more about Tiny, follow us on Twitter or send us a message if you have any questions on how your app could work with localStorage and TinyMCE.

JavascriptDataConfigurationTinyMCE
byBen Long

Computer scientist, storyteller, teacher, and an advocate of TinyMCE. Reminisces about programming on the MicroBee. Writes picture books for kids. Also the wearer of rad shoes. “Science isn’t finished until you share the story.”

Related Articles

  • How-to Use TinyMCEJun 8th, 2023

    How to create gold and silver text effects in TinyMCE

Join 100,000+ developers who get regular tips & updates from the Tiny team.