Lecture 27 - localStorage, indexDB, and Dexie

Administrivia

Pokedex 2 assigned

Exploration session NEXT week

Creative Project 9 - Opt in!!! Melissa's office hours after class

Cookies and Session Recap

Cookies...

  • ...delicious, particularly with chocolate chips.
  • ...are a way to store information or the state of your website.
  • ...can be set so they expire after a time, or after you close the page.
  • ...are kind of a pain to retreive, if there are many cookies that are set already.
  • ...they only allow up to only 4 KB of data storage.
  • ...they can be used by malicious sites to "spy" on browsing behavior.

Sessions...

  • ... are a piece of information stored on the server that keeps track of a single user's state of interaction with the server.
  • ... send back a session ID which is stored on the client in order for the client to keep communicating with their same server session

Ever changing web

New privacy laws in Europe are making website owners rethink using cookies

updated GDPR notice example

localStorage and sessionStorage

storage doors

From Wikipedia

localStorage is a document property that allows you to save information across browser sessions (i.e after you close the browser)

sessionStorage is a document property that allows you to save information for this session only, and will be cleared when the page is closed.

Both localStorage and sessionStorage inherit from Storage class.

Name/value pairs (seen in cookies and Storage) are supported by most every browser

Storage

There are three methods we're interested in from Storage

method description
setItem(keyName, keyValue) Sets the keyName location in localStorage to be keyValue
getItem(keyName) Retrieves the keyValue in localStorage associated with keyName
removeItem(keyName) Removes the keyName location in localStorage

localStorage example


window.localStorage.setItem("Melissa", "Mowgli");
window.localStorage.setItem("Lauren", "Spot");
window.localStorage.setItem("Jacki", "Moss");
let bestPet = window.localStorage.getItem("Lauren");
window.localStorage.removeItem("Jacki");
          

JavaScript (example)

before closing the browser tab

localStorage before example

after closing the browser tab

localStorage after example

sessionStorage example

Similarly for sessionStorage


window.sessionStorage.setItem("Melissa", "Mowgli");
window.sessionStorage.setItem("Lauren", "Spot");
window.sessionStorage.setItem("Jacki", "Moss");
let bestPet = window.sessionStorage.getItem("Lauren");
window.sessionStorage.removeItem("Jacki");
          

JavaScript (example)

before closing the browser tab

sessionStorage before example

after closing the browser tab

sessionStorage after example

indexDB

cookies, localStorage, sessionStorage can only store small amounts of data

indexDB is a "a low-level API for client-side storage of significant amounts of structured data, including files/blobs"

indexDB usage

There are many flavors types of indexDB - so apparently you have to cover your bases with creating the database for your page:


// This works on all devices/browsers, and uses IndexedDBShim as a final fallback
let indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;

// Open (or create) the database
let openDB = indexedDB.open(<dbname>, <version>);
          

JavaScript (template)


// This works on all devices/browsers, and uses IndexedDBShim as a final fallback
let indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;

// Open (or create) the database
let openDB = indexedDB.open("terms", 1);
          

JavaScript (example)

indexDB usage

You need to set callbacks on the new database object, so once the database is created, the tables (schema) can be created.


openDB.onupgradeneeded = function() {
  let db = openDB.result;
  let store = db.createObjectStore("terms", {keyPath: "term"});
  let index = store.createIndex("definition", "definition", { unique: false });
};
openDB.onsuccess = function() {
  console.log("Database created!");
}
          

JavaScript (example)

indexDB setting values


// Start a new transaction
let db = openDB.result;
let tx = db.transaction("terms", "readwrite");
let store = tx.objectStore("terms");
let index = store.index("definition");

// get the term and definition from the user

store.put({key: userTerm, definition: userDef});

// Close the db when the transaction is done
tx.oncomplete = function() {
    db.close();
};
          

JavaScript (example)

indexDB getting values


// assume the variable term has been set
let getValue = store.get(term);

getValue.onsuccess = function() {
    alert(getValue.result.definition);
};

getValue.onerror = function() {
    // error handling here
};
          

JavaScript (example)

Phew... that was a lot of work. And confusing too

Dexie to the rescue

Dexie

Dexie is a wrapper around indexDB that makes it MUCH easier to use.


// create the database (module global)
let db = new Dexie(<name of database>);
window.onload = function() {
    // set up the schema
    db.version(1).stores({
      // this is the table with the columns that are to be indexed.
      <tableName>: '<column1>, <column2>...'
    });
};

JavaScript (template)


let db = new Dexie("definitions");
window.onload = function() {
    // set up the schema
    db.version(1).stores({
      terms: 'term,definition'
    });
};
          

JavaScript (example)

Dexie put

Putting an item in a table is pretty straight forward:


db.<tableName>.put({"column1": <value1>, "column2": <value2>, ...});
          

JavaScript (template)


db.terms.put({"term": term, "definition": definition});
          

JavaScript (example)

Dexie get

There are two ways to get information back out of a table, using either a callback, or a Promise


// get with a callback
db.<tableName>.get(<key>, function (item) {
  // do something here
});
// get with a Promise.
db.<tableName>.get(<key>).then (function (item) {
  // do something here
});
          

JavaScript (template)


db.terms.get(term, function (item) {
  console.log("Callback: Item at " + term + " is " + item.definition);
});

db.terms.get(term).then (function (item) {
    console.log("Promise: Item at " + term + " is " + item.definition);
});
          

JavaScript (example)

Compliance

The one issue with all of these newer technlogies (localStorage, sessionStorage, indexDB, and frameworks like Dexie) is cross browser compatibilty

What Web Can Do Today (Try this in different browsers or on your phone)

Roadmap of Web Applications on Mobile

Can I use - "provides up-to-date browser support tables for support of front-end web technologies on desktop and mobile web browsers."