Connecting to browser local storage

April 02, 2025 | Work: 2025-01

I forget when I realized this, but I had an epiphany.

The problem I was trying to solve was “how do I save a user’s progress in their completionist guides in a way that is front-end only?” The answer was so obvious.

The browser’s local storage:

The localStorage read-only property of the window interface allows you to access a Storage object for the Document’s origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage, except that while localStorage data has no expiration time, sessionStorage data gets cleared when the page session ends — that is, when the page is closed. (localStorage data for a document loaded in a “private browsing” or “incognito” session is cleared when the last “private” tab is closed.)

This is perfect.

So the first thing I needed to do was to create some way to get data into and out of this object. I don’t want to use a JS framework (what fun would that be?) so I wrote up a basic JS class:

class Guide {
  constructor(name) {
    this.name = name;
  }

  get data() {
    return loadFromStorage();
  }

  loadFromStorage() {
    var data = localStorage.getItem(this.name);
    if (data == undefined) {
      data = '{}';
    }
    return JSON.parse(data);
  }

  saveToStorage(data) {
    localStorage.setItem(this.name, JSON.stringify(data));
  }
}

This allowed me to do this:

var z = new Guide('zelda');
-> undefined
z.saveToStorage({ "foo": "bar" });
-> undefined
z.loadFromStorage();
-> {foo: 'bar'}

Heck yes.