Thursday 4 January 2018

javascript - How to detect if browser supports HTML5 Local Storage

itemprop="text">

The following code alerts
ls exist in
IE7:



if(window.localStorage)
{

alert('ls exists');
} else {
alert('ls does
not
exist');
}


IE7
doesn't really support local storage but this still alerts it does. Perhaps this is
because I am using IE9 in IE7 browser and document modes using the IE9 developer tool.
Or maybe this is just the wrong way to test if LS is supported. What is the right
way?



Also I don't want to use Modernizr since I
am using only a few HTML5 features and loading a large script isn't worth it just to
detect support for those few things.


class="post-text" itemprop="text">
class="normal">Answer





You don't have to use modernizr,
but you can use their method to detect if localStorage is
supported



href="https://github.com/Modernizr/Modernizr/tree/master/src"
rel="noreferrer">modernizr at github
href="https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js"
rel="noreferrer">test for
localStorage



//
In FF4, if disabled, window.localStorage should === null.

//
Normally, we could not test that directly and need to do a
// `('localStorage'
in window) && ` test first because otherwise Firefox will
// throw
bugzil.la/365772 if cookies are disabled


// Also in iOS5
& Safari Private Browsing mode, attempting to use localStorage.setItem
//
will throw the exception:
// QUOTA_EXCEEDED_ERRROR DOM Exception
22.
// Peculiarly, getItem and removeItem calls do not
throw.

// Because we are forced to try/catch this, we'll go
aggressive.

// Just FWIW: IE8 Compat mode supports these features
completely:
// www.quirksmode.org/dom/html5.html
// But IE8 doesn't
support either with local
files


Modernizr.addTest('localstorage', function()
{
var mod = 'modernizr';
try {

localStorage.setItem(mod, mod);
localStorage.removeItem(mod);

return true;
} catch(e) {
return false;

}

});


updated
with current source code


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...