IE 11 Unable to get property 'length' of undefined or null reference

可紊 提交于 2020-01-06 01:45:34

问题


I am getting an error in internet explorer 11

"Unable to get property 'length' of undefined or null reference" on line

if (window.localStorage.length !== 0)

it works fine on chrome and Firefox, not sure whats causing it

<script>
    function initialize() {
        // test to see if brouser supports storeage api
        var bSupportsLocal = (('localStorage' in window) && window.localStorage !== null );

        if (!bSupportsLocal) {
            document.getElementById('infoform').innerHTML = "<p> Sorry, This browser does not suport local storage. </p>";
            return;
        }

        if (window.localStorage.length !== 0) {
        document.getElementById('firstName').value = window.localStorage.getItem('firstName');
        $.mobile.navigate("#benefits-facts");
        }
    }

    function storeLocalContent(fName) {
        window.localStorage.setItem('firstName', fName);

        }

        function clearLocalContent(strToStore) {
            window.localStorage.clear();

            }

    window.onload = initialize;
    </script> 

回答1:


I thought in IE window.localStorage is undefined initially. You are checking is localStorage in the window and its not null. So bSupportLocal is setting to true. Its executing window.localStorage.length statement. Undefined.length causing error. Here is the code

     var bSupportsLocal = window['localStorage'] || '';

If localStorage is having some value it will assign to bSupportsLocal, otherwise it is assigned with empty string.



来源:https://stackoverflow.com/questions/31908951/ie-11-unable-to-get-property-length-of-undefined-or-null-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!