copenndthagen
copenndthagen

Reputation: 50732

HTML5 localStorage getItem issue in IE8

I have the following code for localStorage:

function supports_html5_storage() 
{
    try { 
        return 'localStorage' in window && window['localStorage'] !== null; 
    } 
    catch (e) {
        return false; 
    } 
}

function setFormFieldValues()
{
    if (supports_html5_storage()) {
        var retrievedUserDataObj = JSON.parse(localStorage.getItem('UserDataObj'));
        if (retrievedUserDataObj) {
            ...
        }       
    }
}

Now this works fine in Firefox and Chrome, but in IE8, I get the following error:

Unable to get value of the property 'getItem': object is null or undefined

Upvotes: 1

Views: 2681

Answers (1)

ThinkingStiff
ThinkingStiff

Reputation: 65341

Try this. A little more direct if you're already using try/catch.

Demo: jsFiddle

Script:

function supports_html5_storage() {
    try {
        window.localStorage.setItem( 'checkLocalStorage', true );
        window.localStorage.removeItem( 'checkLocalStorage' );
        return true;
    } catch ( error ) {
        return false;
    };
};

document.getElementById( 'result' ).textContent = 
    'localstorage: ' + supports_html5_storage();

HTML:

<div id="result"></div>

Upvotes: 2

Related Questions