在iPhone和iOS 7上使用LocalStorage会抛出这个错误。我一直在寻找一个解决方案,但考虑到我甚至没有私下浏览,没有什么相关的。

我不明白为什么在iOS 7默认禁用localStorage,但它似乎是?我也在其他网站上测试过,但没有成功。我甚至尝试使用http://arty.name/localstorage.html这个网站来测试它,但由于一些奇怪的原因,它似乎根本没有保存任何东西。

有没有人遇到过同样的问题,只是他们很幸运地解决了它?我应该改变我的存储方法吗?

我试图通过只存储几行信息来硬调试它,但没有用。我使用标准的localStorage.setItem()函数保存。


当前回答

2017年4月,一个补丁被合并到Safari中,因此它与其他浏览器保持一致。它随Safari 11一起发布。

https://bugs.webkit.org/show_bug.cgi?id=157010

其他回答

我使用这个返回true或false的简单函数来测试localStorage的可用性:

isLocalStorageNameSupported = function() {
    var testKey = 'test', storage = window.sessionStorage;
    try {
        storage.setItem(testKey, '1');
        storage.removeItem(testKey);
        return true;
    } catch (error) {
        return false;
    }
}

现在您可以在使用localStorage.setItem()之前测试它的可用性。例子:

if ( isLocalStorageNameSupported() ) {
    // can use localStorage.setItem('item','value')
} else {
    // can't use localStorage.setItem('item','value')
}

这个问题和答案帮助我解决了在Parse中注册新用户的一个具体问题。

因为signUp(attrs, options)函数使用本地存储来持久化会话,如果用户处于私有浏览模式,它会抛出“QuotaExceededError: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota.”异常,并且不会调用成功/错误函数。

在我的例子中,因为错误函数从未被调用,它最初似乎是一个问题,在提交上触发单击事件或在注册成功时定义的重定向。

包括一个警告用户解决的问题。

Javascript SDK解析参考 https://parse.com/docs/js/api/classes/Parse.User.html#methods_signUp

用用户名(或电子邮件)和密码注册一个新用户。这将创建一个新的Parse。用户,并在localStorage中持久化会话,以便您可以使用{@link #current}访问该用户。

正如在其他回答中已经解释过的那样,当处于私有浏览模式时,Safari在尝试使用localStorage.setItem()保存数据时总是会抛出这个异常。

为了解决这个问题,我写了一个模仿localStorage的假localStorage,包括方法和事件。

伪localStorage: https://gist.github.com/engelfrost/fd707819658f72b42f55

这可能不是解决这个问题的好办法。对于我的场景来说,这是一个很好的解决方案,因为替代方案是对已经存在的应用程序进行重大重写。

正如在其他答案中提到的,当localStorage时,你总是会在iOS和OS X的Safari私有浏览器模式中获得QuotaExceededError。setItem(或sessionStorage.setItem)被调用。

一种解决方案是在使用setItem的每个实例中执行try/catch或Modernizr检查。

然而,如果你想要一个shim,只是全局地阻止这个错误被抛出,以防止你的JavaScript的其余部分被破坏,你可以使用这个:

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.');
    }
}

2017年4月,一个补丁被合并到Safari中,因此它与其他浏览器保持一致。它随Safari 11一起发布。

https://bugs.webkit.org/show_bug.cgi?id=157010