user900973 user900973 - 1 month ago 14
Javascript Question

Most elegant way to check sessionStorage support?

I have a cookie checker function, which storage a value variable in the var 'cookie1'.
And a sessionStorage storage cookie.

if (cookie1 == '9oz' | sessionStorage.getItem('sessionstoragecookie1') == '9oz')
{
// execute code 1
}
else
{
// execute code 2
}


But sessionStorage is not supported in IE6 and IE7. So it throws an error and breaks the entire script. I could do something like this, but this is absolutely not elegant. What is the most elegant way to work this around?

if (cookie1 == '9oz')
{
// execute code 1
}
else
{
if (typeof(sessionStorage) !='undefined')
{
if (sessionStorage.getItem('sessionstoragecookie1') == '9oz')
{
// execute code 1
}
else
{
// execute code 2
}
}

else
{
// execute code 2
}
}

Answer
if (cookie1 === '9oz' || (window.sessionStorage && window.sessionStorage.getItem('sessionstoragecookie1') === '9oz')) {
    // you've got a 9oz reference 
} else {
    // you haven't :(
}