DOM Exception 22

a short story about why using native APIs directly is probably evil

by

@MichalZalecki

 

ReactJS Wrocław, April 2017

There are likable APIs

  • ServiceWorker

There are vexing APIs

  • IndexedDB

There are sneaky APIs

  • localStorage
  • sessionStorage

There are good and informative errors

Failed to register a ServiceWorker: The user denied permission to use Service Worker.

There are also errors you have to debug

TypeError: Cannot read property 'getItem' of null

DOMException: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.

meanwhile on Chrome

Probably it's Facebook's preview running in WebCromeClient with storage disabled

reason

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

It works on my machine!
(both iPhone and MacBook) 

meanwhile on Safari

Apparently Safari decided to be confusing and this is an error you get when you try to access localStorage in private mode 

reason

function storageFactory(source, prop) {
  let inMemoryStorage = {};

  function setItem(key, value) {
    try {
      getStorage().setItem(key, value);
    } catch (e) {
      inMemoryStorage[key] = value;
    }
  }

  function getItem(key) {
    try {
      return getStorage().getItem(key);
    } catch (e) {
      return inMemoryStorage[key] || null;
    }
  }

  return {
    setItem,
    getItem,
  };
}

export const localStore = storageFactory(window, "localStorage");
export const sessionStore = storageFactory(window, "sessionStorage");

Thanks!

DOM Exception 22

By Michał Załęcki

DOM Exception 22

  • 1,689