Check if localStorage is available

后端 未结 8 1549
悲哀的现实
悲哀的现实 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:12

    With this function you can check if localstorage is available or not, and you keep under control the possible exceptions.

    function isLocalStorageAvailable() {
    
        try {
            var valueToStore = 'test';
            var mykey = 'key';
            localStorage.setItem(mykey, valueToStore);
            var recoveredValue = localStorage.getItem(mykey);
            localStorage.removeItem(mykey);
    
            return recoveredValue === valueToStore;
        } catch(e) {
            return false;
        }
    }
    

提交回复
热议问题