Check if localStorage is available

后端 未结 8 1488
悲哀的现实
悲哀的现实 2020-11-27 02:34

I know there has been many questions about checking for localStorage but what if someone manually shuts it off in their browser? Here\'s the code I\'m using to

8条回答
  •  醉梦人生
    2020-11-27 03:13

    Modifying Joe's answer to add a getter makes it easier to use. With the below you simply say: if(ls)...

    Object.defineProperty(this, "ls", {
      get: function () { 
        var test = 'test';
        try {
          localStorage.setItem(test, test);
          localStorage.removeItem(test);
          return true;
        } catch(e) {
          return false;
        }
      }
    });
    

提交回复
热议问题