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

后端 未结 9 1592
夕颜
夕颜 2020-12-04 05:42

Using LocalStorage on iPhone with iOS 7 throws this error. I\'ve been looking around for a resolvant, but considering I\'m not even browsing in private, nothing is relevant.

9条回答
  •  醉梦人生
    2020-12-04 06:16

    As mentioned in other answers, you'll always get the QuotaExceededError in Safari Private Browser Mode on both iOS and OS X when localStorage.setItem (or sessionStorage.setItem) is called.

    One solution is to do a try/catch or Modernizr check in each instance of using setItem.

    However if you want a shim that simply globally stops this error being thrown, to prevent the rest of your JavaScript from breaking, you can use this:

    https://gist.github.com/philfreo/68ea3cd980d72383c951

    // Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem
    // throw QuotaExceededError. We're going to detect this and just silently drop any calls to setItem
    // to avoid the entire page breaking, without having to do a check at each usage of Storage.
    if (typeof localStorage === 'object') {
        try {
            localStorage.setItem('localStorage', 1);
            localStorage.removeItem('localStorage');
        } catch (e) {
            Storage.prototype._setItem = Storage.prototype.setItem;
            Storage.prototype.setItem = function() {};
            alert('Your web browser does not support storing settings locally. In Safari, the most common cause of this is using "Private Browsing Mode". Some settings may not save or some features may not work properly for you.');
        }
    }
    

提交回复
热议问题