scottjehl/Device-Bugs

(iOS/Safari) localStorage in private mode has quota=0 and always throws on write

Opened this issue · 0 comments

Platforms:

Safari on iOS

Summary:

When a new tab is launched in private mode, localStorage has zero quota assigned and hence always throws when trying to write to it.

Example:

localStorage.setItem('test', 1) // throws QUOTA_EXCEEDED_ER

Workarounds:

The best bet could be to try-catch and silently fail when saving to localStorage (depending if localStorage is critical for the app to work or not).

Since it would be mundane and error-prone to always wrap any localStorage.setItem call with a try-catch, you could create a global localStorageWrapper (and ban the direct localStorage access in JSHint for instance) like this (snippet for Object.create-supporting browsers)

var StorageWrapperProto = function(underlyingStorage) {
    return {
      key: function(n) {
        return underlyingStorage.key(n);
      },

      clear: function() {
        underlyingStorage.clear();
      },

      getItem: function(key) {
        return underlyingStorage.getItem(key);
      },

      setItem: function(key, value) {
        try {
          underlyingStorage.setItem(key, value);
        } catch (e) {
          window.console.error("Error writing to the storage for key = " + key +
            "! (this is expected in private mode in Safari)");
        }
      },

      removeItem: function(key) {
        underlyingStorage.removeItem(key);
      }
    };
};

window.localStorageWrapper = Object.create(new StorageWrapperProto(window.localStorage));
window.sessionStorageWrapper = Object.create(new StorageWrapperProto(window.sessionStorage));

StackOverflow discussions:

http://stackoverflow.com/questions/14555347/html5-localstorage-error-with-safari-quota-exceeded-err-dom-exception-22-an