简体   繁体   中英

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM