Forum Moderators: open

Message Too Old, No Replies

Checking if Storage is supported

         

csdude55

6:57 am on Sep 4, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm currently using this to either show the result of sessionStorage, or if typeof(Storage) is undefined then it tries a function that reads a cookie, and as a last resort it return false.

Like so:

var saveName = 'blahblahblah';

getObj = JSON.parse(
typeof(Storage) !== 'undefined' ?
sessionStorage.getItem(saveName) || false :
getCookie(saveName) || false
);


(where getCookie() is a function defined separately, and not really relevant to this thread)

I'm not able to test on older browsers, but am I right that this would work just as well?

var saveName = 'blahblahblah';

getObj = JSON.parse(
window.sessionStorage.getItem(saveName) ||
getCookie(saveName) ||
false
);

ronin

12:52 pm on Oct 1, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



One way to check if sessionStorage is supported would be to run:


Object.keys(window).indexOf('localStorage') > -1;


This will return true if there is support and false if not.

ronin

3:11 pm on Oct 1, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Probably a more verbose explanation would be helpful.

Essentially, the browser's global window object has a lot of entries - and many of these conveniently indicate (simply by being present) that the browser supports that particular feature.

Because of this you can usually query:

if (Object.keys(window).indexOf('myFeature') > -1) { [...] }


or, more concisely:

if ('myFeature' in window) { [...] }


and that will reveal browser support.

ronin

8:33 am on Oct 2, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



In much the same vein, if you want to see a full list of global window object entries, simply run:

console.log(window)