localStorage 是 HTML5 存储数据的方式,之前初次整理过其用法及不同存储类型,详情查看《js中local/session 及cookie存储数据》,稍微回顾一下localStorage的特点:

  1. 受同源策略的限制
  2. 存储空间一般在 5MB 左右
  3. 键值对最终的存储形式为字符串
  4. 数据可以长期保留,只有不清理,一年后也能用!

兼容性检测代码:

window.onload = function(){ 
  if (isLocalStorageUsable()) { // 判断设备兼容后执行
  	console.log((isLocalStorageUsable()));
  	aa()
  } 
}
function isLocalStorageUsable() {
    const localStorageTestKey = '__localStorage_support_test';
    const localStorageTestValue = 'test';
    let isSupport = false;
    try {
      localStorage.setItem(localStorageTestKey, localStorageTestValue);
      if (localStorage.getItem(localStorageTestKey) === localStorageTestValue) {
        isSupport = true;
      }
      localStorage.removeItem(localStorageTestKey);
      return isSupport;
    } catch(e) {
        if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
	      console.warn('localStorage 存储已达上限!')
	    } else {
	      console.warn('当前浏览器不支持 localStorage!');
	    }
	    return isSupport;
    }
} 
function aa(){ // 开始存数据
 	localStorage.setItem('myCat', 'Tom');
}

版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。
转载请注明来源:JS中localStorage兼容性检测 - Qui-Note