IE8 and localStorage support [duplicate]

2019-02-18 11:52发布

问题:

This question already has an answer here:

  • Does IE8 out-of-the-box have support for 'localStorage' 5 answers

I am not sure if IE8 fully supports localStorage. But I use the following method to detect

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

Now IE returns true for 'localStorage' in window

But returns undefined for window['localStorage']

So should I update this method OR does IE8 indeed have local storage support ?

回答1:

You can try to set and read localStorage.

Some browsers return a security error if cookies are disabled or you are working with file: protocol.

function hasStorage(){
    try{
        localStorage.setItem('test', '7');
        if(localStorage.getItem('test')=== '7'){
            localStorage.removeItem('test');
            return true;
        }
    }
    catch(er){}
    return false;
}

alert(hasStorage())



回答2:

Here is a famous localStorage plugin https://github.com/marcuswestin/store.js/ you can add, edit and delete datas very easily and the most important is you can use localstorage in IE6+.

store.js uses localStorage when available, and falls back on the userData behavior in IE6 and IE7. No flash to slow down your page load. No cookies to fatten your network requests. Ex :

store.set('user', { name: 'marcus', likes: 'javascript' })


回答3:

You can use Modernizr:

if (Modernizr.localstorage) {
  // localStorage is available
}