Lesson 13 localStorage

Mark Harder, 04 January 2019

Store Variable Data Between Browser Sessions

What happens to our JavaScript variables when the user Reloads the page?

  • Pull up the lesson 12 Tic Tac Toe game code, then open the index.html in the chrome browser. Click a few boxes to add X’s and O’s. This updates the gameState.board object variable. If you reload the page (F5 or click the button), all your progress will disappear, and the variables will be set again to their initial state. This happens because a reload of a page in a browser starts fresh with blank memory then loads the HTML and JavaScript before running it again fresh.
  • If you open the index.html again in another Browser tab you will also start with fresh variables because JavaScript variables run in separate sandboxes/memory spaces between tabs.
  • How do we make the code variables share data between tabs, or remember between reloads?

Storage Object

We access a Storage object by calling either localStorage or sessionStorage. Storage provides access to a particular domain’s session or local storage.

  • What is the domain? When you browse a website like https://www.google.com/, that is the Google’s domain. When you access https://www.bing.com/, that is another domain. In order to protect the security and functionality of a website, browsers prevent cross-domain access. This means that Code on the Google domain can’t read or write storage on another Tab or Window, that is on Bing’s domain.

localStorage vs sessionStorage

The data stored in localStorage is available for the same domain, across multiple tabs and windows with no expiration. SessionStorage is accessible only for the lifetime of the current tab, this means that reloads of the page will not clear sessionStorage. SessionStorage will also be different between tabs and windows.

  • localStorage ~5MB memory, saved for infinity or until the user manually deleted it.
  • sessionStorage ~5MB memory, saved for the life of the current tab.
  • Uninstalling the reinstalling the Google browser will clear localStorage. Some updates to the browsers might also clear localStorage.
  • In Chrome press Ctrl-Shift-Del to bring up the “Clear browsing data” screen. On the Advanced Tab, localStorage can be cleared using the “Hosted app data” item.

There are 4 methods and 1 property we use to work with Storage.

Storage.setItem(key, data) Add basic data item to localStorage or sessionStorage

  • Key is unique string used to store and retrieve a data value which is also a string.

    localStorage.setItem(‘varName’, ‘data value’);

or example using sessionStorage

sessionStorage.setItem(‘varName’, ‘data value’);

Storage.getItem(key) Retrieve basic data item from localStorage or sessionStorage

  • Key is the key string used with setItem to save a data value, which is a string. If the item can’t be found a null will be returned.

    let resultString = localStorage.getItem(‘varName’);

Storage.removeItem(key) Delete an existing data item from localStorage or sessionStorage

  • Key is the key string used with setItem to save a data value, which is a string. There is no error if the item doesn’t exist in storage.

    localStorage.removeItem(‘varName’);

Storage.clear() Clear all items

localStorage.setItem(‘varName’, ‘data value’);


Storing Object Data in Storage

Because Storage can only store a key data pair as a string, we need a way to convert complex object variables into a string and then back. First I will present the code, then explain what JSON is.

  • Convert and object variable into a string and save it in localStorage.

    let complexObj = { firstName: “Mark”, lastName: “Harder”, isTeacher: true };
    localStorage.setItem(“TeacherObject”, JSON.stringify(complexObj));

  • Retrieve the string of our object from storage and convert it back to an object.

    complexObj = JSON.parse(localStorage.getItem(“TeacherObject”));

JSON stands for JavaScript Object Notation

JSON is a lightweight format for storing and transporting data JSON is often used when data is sent from a server to a web page Here is an example of a JSON string (or it could be a file) that stores people objects in an array

{
"people":[
    {"firstName":"Mark", "lastName":"Harder"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]
}

JavaScript Object Notation

The JSON format is syntactically identical to the code for creating JavaScript objects.
Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects.

JavaScript Code for JSON

  • JSON.stringify() function
    • JavaScript has a built-in function to convert an object into JSON format.
    • In JSON, date objects are not allowed. The JSON.stringify() function will convert any dates into strings.
  • JSON.parse() function
    • JavaScript has a built-in function to convert a string, written in JSON format, into native JavaScript objects: See the Storage Examples above.
    • Make sure the text is written in JSON format, or else you will get a syntax error.

JSON Syntax Rules

Data is in name/value pairs
Data is separated by commas
Curly braces hold objects {}
Square brackets hold arrays

Valid Data Types

In JSON, values must be one of the following data types:

  • a string
  • a number
  • an object (JSON object)
  • an array
  • a boolean
  • null

JSON Strings

Strings in JSON must be written in double quotes.

{ “firstName”:”Mark” }

JSON Numbers

Numbers in JSON must be an integer or a floating point.

{ “age”:30 }

JSON Objects

Values in JSON can be objects.

{ “people”:[ “Mark”, “Anna”, “Peter” ] }

JSON Booleans

Values in JSON can be true/false.

{ “isTeacher”:true }

JSON null

Values in JSON can be null.

{ “middleName”:null }


Assignment due for discussion next class and checked into GitHub by the Monday after that.

  • Create a new repo called lesson13
  • Start with the code from lesson 12 https://github.com/mhintegrity/lesson12 code
  • Create a function called LoadBoardState()
    • Check for an item in localStorage called “TicTacToe”
    • if the item exists, convert its JSON string back to a value to store in gameState variable
  • Create a function called SaveBoardState()
    • save the current state of gameState into an item in localStorage called “TicTacToe”
    • gameState is an object to make sure to convert it to a JSON string
  • Add a call to the function SaveBoardState() each time the gameState variable is changed
  • Add a call to the function LoadBoardState() in InitializeBoardState()
  • Test your code to see if closing and reopening your page remembers its last state.