IE8中的HTML5 localStorage getItem问题

时间:2013-03-10 05:00:29

标签: javascript html5 internet-explorer-8 local-storage

我有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) {
            ...
        }       
    }
}

现在这在Firefox和Chrome中运行良好,但在IE8中,我收到以下错误:

  

无法获取属性'getItem'的值:object为null或undefined

1 个答案:

答案 0 :(得分:2)

试试这个。如果您已经在使用try/catch,那就更直接了。

演示: jsFiddle

脚本:

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>