Nic*_*icT 218 javascript iphone html5 local-storage
在iOS 7上使用iPhone上的LocalStorage会抛出此错误.我一直在寻找一个解决方案,但考虑到我甚至没有私下浏览,没有任何相关性.
我不明白为什么在iOS 7中默认禁用localStorage,但它似乎是?我也在其他网站上测试过,但没有运气.我甚至尝试使用这个网站测试它:http://arty.name/localstorage.html,但它似乎并没有因为一些奇怪的原因而保存任何东西.
有没有人有同样的问题,只有他们有运气修复它?我应该切换我的存储方法吗?
我只是通过存储几行信息来尝试进行硬调试,但无济于事.我使用标准localStorage.setItem()功能来保存.
小智 371
当Safari处于私有模式浏览时,可能会发生这种情况.在私密浏览中,本地存储根本不可用.
一种解决方案是警告用户应用程序需要非私有模式才能工作.
更新:这已在Safari 11中修复,因此行为现在与其他浏览器对齐.
phi*_*reo 103
如其他答案中所述,当调用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.');
}
}
Run Code Online (Sandbox Code Playgroud)
Dre*_*ewT 16
我使用这个简单的函数,它返回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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以localStorage.setItem()在使用之前测试可用性.例:
if ( isLocalStorageNameSupported() ) {
// can use localStorage.setItem('item','value')
} else {
// can't use localStorage.setItem('item','value')
}
Run Code Online (Sandbox Code Playgroud)
我碰巧在iOS 7中遇到了同样的问题(某些设备没有模拟器).
看起来iOS 7中的Safari具有较低的存储配额,这显然是通过具有长历史记录来实现的.
我想最好的做法是捕捉异常.
Modernizr项目有一个简单的补丁,您应该尝试类似的东西:https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
| 归档时间: |
|
| 查看次数: |
127949 次 |
| 最近记录: |