Skip to content

Instantly share code, notes, and snippets.

@EddiG
Last active September 21, 2017 08:43
Show Gist options
  • Save EddiG/2dc1a7d008a69e254b0ed51ae74ef1c4 to your computer and use it in GitHub Desktop.
Save EddiG/2dc1a7d008a69e254b0ed51ae74ef1c4 to your computer and use it in GitHub Desktop.

Polyfill for localStorage in Safari private browsing mode

Inspired by https://gist.github.com/juliocesar/926500

function getLocalStorage() {
  try {
    window.localStorage.setItem('__test-localstorage__', '1');
    window.localStorage.removeItem('__test-localstorage__');
    return window.localStorage;
  } catch (error) {
    const localStorage = {
      data: {},
      setItem(id, val) {
        this.data[id] = String(val);
      },
      getItem(id) {
        // eslint-disable-next-line no-prototype-builtins
        return this.data.hasOwnProperty(id) ? this.data[id] : null;
      },
      removeItem(id) {
        return delete this.data[id];
      },
      clear() {
        this.data = {};
      },
    };
    return localStorage;
  }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment