Blueprint by Tiny
Return to Tiny.cloud
Return to Tiny.cloudTry TinyMCE for Free
Search by

Javascript and localStorage in a nutshell

Ben Long

February 6th, 2020

Written by

Ben Long
Ben Long

Category

Tips & How-Tos

Sometimes you want to get something done in HTML without the added complexity of a backend database. In this case, you can use Javascript to access localStorage.

But, first...

...we need to understand exactly what we're dealing with; for example, what exactly is localStorage, when can you use it, and is it secure?

If you already know what you’re getting yourself into, you can skip ahead to:

Otherwise, read on...

What is localStorage?

localStorage allows web applications to store data locally within the user's browser with no expiration date. The data will not be deleted when the browser is closed, and will be available when the browser is opened again.

The good, the bad, and the ugly of localStorage

The good

  • 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.

The bad

  • 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.

The ugly

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

Okay. Now that we’ve got the housekeeping out of the way, let’s get into it!

Javascript localStorage methods

There are four basic javascript 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)

I always think the best way to really understand something is to try it out for yourself. So...

Open your browser console, for example, by opening Developer Tools in Google Chrome and clicking on the Console tab.

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

> localStorage
< Storage {length: 0}

Enter localStorage.setItem('myKey', 'testValue') and the string testValue will be stored against the key myKey:

> localStorage.setItem('myKey', 'testValue')
< undefined

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

> localStorage
< Storage {myKey: "testValue", length: 1}

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

> localStorage.getItem('myKey')
< "testValue"

setItem() and getItem() are the two methods we’ll be using in our example. Feel free to try out the other methods too in a similar way.

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

Javascript localStorage example

Let’s put these methods into practice.

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>

We’ve defined two Javascript functions, mySave() and myLoad(). The buttons are configured so that, when they are clicked, they each trigger the relevant Javascript function. document.getElementById() is used to get/set the value of the element specified. In this case, we are 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.

Once you’ve created the above HTML file, open it in a browser. What it looks like on your screen will depend on your CSS. (We inserted some custom CSS for the buttons in our example to make them look a little more interesting than the default.)

Javascript localStorage example running in a browser.

Test it

Type something in the textarea and click Save. The content will be saved to localStorage. Then, refresh the page, and the content will disappear. Now, click Load and the content will be retrieved from localStorage and appear in the textarea as before.

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.

That’s all there is to it! But why not try taking it a step further...

Javascript localStorage example with WYSIWYG editor

A basic textarea is going to be enough in some cases, but at other times your users will want to write more than simple text; and integrating the TinyMCE WYSIWYG rich text editor is super easy to do.

Javascript localStorage example with WYSIWYG rich text editor.

Add the editor

Continuing with the previous example, include the following code in the head section <head>...</head> of your HTML. This will add the TinyMCE editor to your page, effectively replacing the textarea identified by selector in the configuration options.

<script src='https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js' referrerpolicy="origin"></script>
<script>
  tinymce.init({
    selector: '#myTextarea',
    height: 400,
    plugins: 'lists, link, image, media',
    toolbar: 'h1 h2 bold italic strikethrough blockquote bullist numlist forecolor backcolor | link image media | removeformat help',
    menubar: false
  });
</script>

Replace no-api-key with your own Tiny API Key. If you don’t already have one, you can get a free API Key directly from Tiny now (includes a 30 day trial of the premium plugins).

NOTE: If you open the file in your browser at this point, you may still see a warning message even once you’ve included your own API Key. To remove it you’ll need to:

  1. Host the file on a server (localhost is fine).
  2. Register your domain against the API Key in the Tiny account dashboard (unless you’re running it on localhost — localhost is already registered by default). There might be a short delay while the update propagates across our global CDN.

In our example, we’ve provided some additional config to customize the plugins and options available on the toolbar. There’s a huge range of core and premium features that can be added (or removed) as needed.

Link the buttons

Although the editor is now on the page, and you can enter text and format it with all the options, the Save and Load buttons will no longer work. So we just need to make a few extra tweaks to get them working again.

First, we’ll tweak the mySave() function. Instead of getting the value from the textarea, we’ll make use of the getContent() function, from the extensive TinyMCE API, to access the editor contents. So we’ll modify the function as follows. Note that you can refer to the editor by the id of the element that it replaced, in this case myTextarea.

function mySave() {
  var myContent = tinymce.get("myTextarea").getContent();
  localStorage.setItem("myContent", myContent);
}

Modify the myLoad() function in a similar way, using the TinyMCE setContent() function.

function myLoad() {
  var myContent = localStorage.getItem("myContent");
  tinymce.get("myTextarea").setContent(myContent);
}

Test it

Open the file, type some text in the editor, and click Save. (I pasted in a bit of prose from Frankenstein in the image above.) Then refresh the page, click Load, and the saved content will appear.

Do we really need the load button?

In practice, instead of a load button, we would often want our saved content to be loaded automatically.

We’ll do this by adding the setup option to the TinyMCE initialization script, defining a callback that will be executed before the TinyMCE editor instance is rendered. In this case, on initialization we want to set the content based on what is in localStorage.

<script>
  tinymce.init({
    selector: '#myTextarea',
    height: 400,
    plugins: 'lists, link, image, media',
    toolbar: 'h1 h2 bold italic strikethrough blockquote bullist numlist forecolor backcolor | link image media | removeformat help',
    menubar: false,
    setup: function (editor) {
      editor.on('init', function (e) {
        editor.setContent(localStorage.getItem("myContent");
      });
    }
  });
</script>

You can also delete the myLoad() function and the Load button since they’re no longer being used.

Now, open the file in your browser, type some text in the editor, and click Save. Then refresh the page and the saved content will be populated in the editor automatically from localStorage.

What’s next?

This is only the tip of the iceberg when it comes to Javascript and rich text editing. Check out some of our related content:

If you’d like to know more about Tiny, follow us on Twitter or send us a message. You can also reach out to me on Twitter directly.

Javascript
Ben Long
byBen Long

Developer Advocate at Tiny. Computer scientist turned storyteller. 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

  • Visual depiction of Tiny and Angular integration
    Tips & How-Tos

    How to add TinyMCE 5 to a simple Angular project

    by Simon Fjeldså in Tips & How-Tos

Build beautiful content for the web with Tiny.

The rich text editing platform that helped launch Atlassian, Medium, Evernote and more.

Begin my FREE 30 day trial
Tiny Editor