scottjehl / Device-Bugs

Just a collection of quirks and issues that occur on browser platforms (particularly those unlikely to update)
864 stars 19 forks source link

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

Open jakub-g opened 9 years ago

jakub-g commented 9 years ago

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