Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most elegant way to check sessionStorage support?

Tags:

javascript

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
        }
}
like image 776
user900973 Avatar asked Aug 25 '11 14:08

user900973


People also ask

How long is sessionStorage accessible?

The sessionStorage object stores data for only one session. (The data is deleted when the browser is closed).

Is sessionStorage cleared on refresh?

sessionStorage is similar to localStorage ; the difference is that while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends.


1 Answers

if (cookie1 === '9oz' || (window.sessionStorage && window.sessionStorage.getItem('sessionstoragecookie1') === '9oz')) {
    // you've got a 9oz reference 
} else {
    // you haven't :(
}
like image 112
Matt Avatar answered Oct 22 '22 01:10

Matt