开发HTML5 webapp时经常需要使用本地存储,如localStorage和sessionStorage存储一些数据,相比最多能存4k的cookie相比,用起来很好用。 但是localStorage在iOS Safari、chrome和UC浏览器中的隐私模式(也叫无痕模式)下无法使用,代码执行不下去,手机Safari浏览器中具体表现是:
- 1 localStorage对象仍然存在
- 2 但是setItem会报异常:QuotaExceededError
- 3 getItem和removeItem直接忽略
Safari中控制台截图:
判断浏览器是否支持localStorage的方法:
function isLocalStorageSupported() {
var testKey = 'test',
storage = window.sessionStorage;
try {
storage.setItem(testKey, 'testValue');
storage.removeItem(testKey);
return true;
} catch (error) {
return false;
}
}
在此,推荐一波Github上 已做简单封装的js(https://github.com/hehaibao/cacheJS),包括了检测是否支持storage的检测和增删改,cookie的增删改。
Comments