Check if localStorage is available

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

    I'd check that localStorage is defined prior to any action that depends on it:

    if (typeof localStorage !== 'undefined') {
        var x = localStorage.getItem('mod');
    } else {
        // localStorage not defined
    }
    

    UPDATE:

    If you need to validate that the feature is there and that it is also not turned off, you have to use a safer approach. To be perfectly safe:

    if (typeof localStorage !== 'undefined') {
        try {
            localStorage.setItem('feature_test', 'yes');
            if (localStorage.getItem('feature_test') === 'yes') {
                localStorage.removeItem('feature_test');
                // localStorage is enabled
            } else {
                // localStorage is disabled
            }
        } catch(e) {
            // localStorage is disabled
        }
    } else {
        // localStorage is not available
    }
    
    0 讨论(0)
  • 2020-11-27 03:34

    Here is an easy check:

    if(typeof localStorage === 'undefined'){

    0 讨论(0)
提交回复
热议问题