18. Local Storage

There are other options besides cookies for keeping data associated with a client. The newest is something called local storage.

You can access the local storage from JavaScript using a built in object named localStorage. Try opening up a console in your web browser and type it in followed by a period. You can see some of the options.

Using it is easy, the object has setItem and getItem methods where we can store data in key/value pairs.

Anything stored with localStorage should stay around even when the browser window closes. Is your data more transient? Don’t need it to stay when the web page closes? Use sesssionStorage. It has the same interface.

Screenshot of our sample app in use:

../../_images/screenshot.png

HTML for the sample app. It has the fields we want.

Note that there are no buttons. We run the JavaScript and save after any change in the form. This can be handy if there’s a problem submitting the form, you don’t lose your data.

local_storage.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<!DOCTYPE html>

<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
    <title>Sample Form</title>
</head>

<body>

<!-- Navigation Bar -->
<nav class="navbar navbar-inverse">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>

                <!-- Three line "hamburger" icon for the collapsed navigation -->
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>

            <!-- Title on nav bar -->
            <a class="navbar-brand" href="#">CIS 320</a>
        </div>

        <div id="navbar" class="collapse navbar-collapse">
            <ul class="nav navbar-nav">
                <li class="active"><a href="index.html">Home</a></li>
                <li><a href="javascript_assignment.html">Javascript Assignment</a></li>
                <li><a href="test_javascript.html">Test Javascript</a></li>
                <li><a href="name_list.html">Name List</a></li>
                <li><a href="form_demo.html">Form Demo</a></li>
                <li><a href="cookie_demo.html">Cookie Demo</a></li>
                <li><a href="session_demo.html">Session Demo</a></li>
                <li><a href="local_storage.html">Local Storage</a></li>
            </ul>
        </div>
    </div>
</nav>

<div class="container">
    <h1>HTML Local Storage Objects</h1>

    <h2>Local Storage</h2>
    <p>This is <em>local</em> storage. Local storage is stored on the client. It will
        <em>persist</em> after the client closes the browser.</p>
    <textarea id="htmlFormFieldForLocalStorage" rows="6" cols="80"></textarea>

    <h2>Session Storage</h2>
    <p>This is <em>session</em> storage. Session storage is also stored on the client. It will
        <em>go away</em> after the client closes the browser.</p>
    <textarea id="htmlFormFieldForSessionStorage" rows="6" cols="80"></textarea>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.3.7/js/tether.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="local_storage.js"></script>
</body>
</html>

…and here’s the fun stuff. The JavaScript.

local_storage.js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// --- This code runs on start-up of the page.

// -- Local Storage Example
// Local storage has no expiration, and stays if page closes.

// First, see if there is any data stored in local storage
// for the key "myLocalStorageKey".
var textContent = localStorage.getItem("myLocalStorageKey");

// If there is data, initialize the form field with the data.
// Otherwise, don't.
if(textContent){
    console.log("Initialized with saved data.");
    $('#htmlFormFieldForLocalStorage').val(textContent);
} else {
    console.log("No saved data.");
}

// -- Local Session Example
// Local session is just like local storage, but goes away
// when the page session ends. (If page closes.)

// First, see if there is any data stored in local storage
// for the key "myLocalStorageKey".
textContent = sessionStorage.getItem("mySessionStorageKey");

// If there is data, initialize the form field with the data.
// Otherwise, don't.
if(textContent){
    console.log("Initialized with saved data.");
    $('#htmlFormFieldForSessionStorage').val(textContent);
} else {
    console.log("No saved data.");
}

// --- This runs when we change the text in the FIRST (storage) text field
$('#htmlFormFieldForLocalStorage').bind("input", function(e) {
    if (typeof(Storage) === "undefined") {
        console.log("Sorry, no local storage available.");
        return;
    }
    localStorage.setItem("myLocalStorageKey", $('#htmlFormFieldForLocalStorage').val());
});

// --- This runs when we change the text in the SECOND (session) text field
$('#htmlFormFieldForSessionStorage').bind("input", function(e) {
    if (typeof(Storage) === "undefined") {
        console.log("Sorry, no local storage available.");
        return;
    }
    sessionStorage.setItem("mySessionStorageKey", $('#htmlFormFieldForSessionStorage').val());
});

Try it out here: here.

You can store about 10 meg of data combined for the local and session data. This is way more than the 4000 character limit you get with cookies.

If you need something more structured than simple key/value pairs, you can create your own database using IndexedDB. Think, you can download a database and then allow the user to interact with the data all locally. This is WAY faster than going back and forth from the server for everything.