localStorage sessionStorage
生存周期 一直 在关闭页面后即被清空
大小限制 各个浏览器不一样。chrome限制为5m

捕获存储异常

  1. try {
  2. localStorage.setItem(key, value);
  3. } catch (oException) {
  4. if (oException.name === 'QuotaExceededError') {
  5. console.log('超出本地存储限额!');
  6. // 清空后,再设置
  7. localStorage.clear();
  8. localStorage.setItem(key, value);
  9. }
  10. }

获取存储大小限制

  1. (function() {
  2. if (!window.localStorage) {
  3. console.log('当前浏览器不支持localStorage!')
  4. }
  5. var test = '0123456789';
  6. var add = function(num) {
  7. num += num;
  8. if (num.length == 10240) {
  9. test = num;
  10. return;
  11. }
  12. add(num);
  13. }
  14. add(test);
  15. var sum = test;
  16. var show = setInterval(function() {
  17. sum += test;
  18. try {
  19. window.localStorage.removeItem('test');
  20. window.localStorage.setItem('test', sum);
  21. console.log(sum.length / 1024 + 'KB');
  22. } catch (e) {
  23. alert(sum.length / 1024 + 'KB超出最大限制');
  24. clearInterval(show);
  25. }
  26. }, 0.1)
  27. }
  28. )()

获取当前存储的size

  1. // 示例代码
  2. function get_cache_size(t) {
  3. t = t == undefined ? "l" : t;
  4. var obj = "";
  5. if (t === 'l') {
  6. if (!window.localStorage) {
  7. console.log('浏览器不支持localStorage');
  8. } else {
  9. obj = window.localStorage;
  10. }
  11. } else {
  12. if (!window.sessionStorage) {
  13. console.log('浏览器不支持sessionStorage');
  14. } else {
  15. obj = window.sessionStorage;
  16. }
  17. }
  18. if (obj !== "") {
  19. var size = 0;
  20. for (item in obj) {
  21. if (obj.hasOwnProperty(item)) {
  22. size += obj.getItem(item).length;
  23. }
  24. }
  25. console.log('当前已用存储:' + (size / 1024).toFixed(2) + 'KB');
  26. }
  27. }
  28. get_cache_size('l'); //localStorage当前大小
  29. get_cache_size('s'); //sessionStorage当前大小