如其他答案中所述,调用localStorage.setItem
(或sessionStorage.setItem
)时,在iOS和OS X上的Safari私有浏览器模式下,您始终会收到QuotaExceededError 。
一种解决方案是在使用的每个实例中进行try / catch或Modernizr检查setItem
。
但是,如果您希望使用仅在全局范围内阻止抛出此错误的填充程序,以防止其他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.');
}
}