20

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
        }
}
user900973
  • 323
  • 2
  • 3
  • 9

6 Answers6

15
if (cookie1 === '9oz' || (window.sessionStorage && window.sessionStorage.getItem('sessionstoragecookie1') === '9oz')) {
    // you've got a 9oz reference 
} else {
    // you haven't :(
}
Matt
  • 74,352
  • 26
  • 153
  • 180
  • Sadly, this part `&& window.sessionStorage.getItem('sessionstoragecookie1') == '9oz' ` will throw a object or method is not supported in Internet Explorer 6/7. – user900973 Aug 25 '11 at 15:07
  • 5
    @user900973: Shouldn't do, because I first check that window.sessionStorage exists; and that code will only execute if it does. – Matt Aug 25 '11 at 15:21
7
if(typeof(sessionStorage) == 'undefined')
{
    sessionStorage = {
        getItem: function(){},
        setItem: function(){},
        clear: function(){},
        removeItem: function(){}
    };
}

And now use as usual. It will always return NULL

But I would consider this script

http://code.google.com/p/sessionstorage/

This will enable sessionStorage in every browser.

Sergey Romanov
  • 2,949
  • 4
  • 23
  • 38
  • technically need to define : clear & removeItem as well if you are going to mock the storage api – MikeT Apr 03 '19 at 13:23
6

I would use try/catch to check if the browser supports sessionStorage.

function isSessionStorageSupported() {
    try {
      var storage = window.sessionStorage;
      storage.setItem('test', 'test');
      storage.removeItem('test');    
      return true;
    } catch (e) {
      return false;
    }
}

Use the function like this:

 if (isSessionStorageSupported()) {
   // do something with it
 } else {
  // have a fallback code here
}
Ravi
  • 191
  • 2
  • 6
  • 3
    This answer worked for me when I moved the `var storage...` line into the try/catch block. Any of the other answers here which involved `window.sessionStorage` outside of a try/catch block produced the error `Uncaught DOMException: Failed to read the 'sessionStorage' property from 'Window': Access is denied for this document` for me. – Employee Feb 22 '19 at 21:34
  • how to test it? – Yatin Mistry Jun 22 '22 at 10:58
  • @YatinMistry You will need to mock it. Some examples here https://stackoverflow.com/questions/11485420/how-to-mock-localstorage-in-javascript-unit-tests – Ravi Aug 10 '22 at 20:39
3
function checkSessionStorage()
{
   return window.sessionStorage;
}

If it is undefined then sessionStorage is not supported.

Matt
  • 74,352
  • 26
  • 153
  • 180
Tarik
  • 79,711
  • 83
  • 236
  • 349
  • 1
    What's the benefit for the code above to use this instead of `if (typeof(sessionStorage) !='undefined')`? – user900973 Aug 25 '11 at 15:26
0

You can try something like this: What it does is that if a browser doesn't support sessionStorage, it clears the session.

try { 
   sessionStorage.setItem('name','value'); 
}
catch(e){
if(e.code == 22){ 
   sessionStorage.clear(); }
} 
0

I know I'm a little late to the party, but I have a few useful functions I cooked up and threw into a file named 'manage_storage.js'. I hope they are as useful to you guys, as they have served me well.

Here is my code:

/* Conditional Function checks a web browser for 'session storage' support. [BEGIN] */

if (typeof isSessStorageAllowed !== 'function')
    {
        function isSessStorageAllowed()
            {
                if (!!window.sessionStorage && typeof sessionStorage.getItem === 'function' && typeof sessionStorage.setItem === 'function' && typeof sessionStorage.removeItem === 'function')
                    {
                        try
                            {
                                var cur_dt = new Date();
                                var cur_tm = cur_dt.getTime();
                                var ss_test_itm_key = 'ss_test_itm_' + String(cur_tm);
                                var ss_test_val = 'ss_test_val_' + String(cur_tm);

                                sessionStorage.setItem(ss_test_itm_key, String(ss_test_val));

                                if (sessionStorage.getItem(ss_test_itm_key) == String(ss_test_val))
                                    {
                                        return true;
                                    }
                                else
                                    {
                                        return false;
                                    };

                                sessionStorage.removeItem(ss_test_itm_key);
                            }
                        catch (exception)
                            {
                                return false;
                            };
                    }
                else
                    {
                        return false;
                    };
            };
    };

/* Conditional Function checks a web browser for 'session storage' support. [END] */

/* Conditional Function checks a web browser for 'local storage' support. [BEGIN] */

if (typeof isLclStorageAllowed !== 'function')
    {
        function isLclStorageAllowed()
            {
                if (!!window.localStorage && typeof localStorage.getItem === 'function' && typeof localStorage.setItem === 'function' && typeof localStorage.removeItem === 'function')
                    {
                        try
                            {
                                var cur_dt = new Date();
                                var cur_tm = cur_dt.getTime();
                                var ls_test_itm_key = 'ls_test_itm_' + String(cur_tm);
                                var ls_test_val = 'ls_test_val_' + String(cur_tm);

                                localStorage.setItem(ls_test_itm_key, String(ls_test_val));

                                if (localStorage.getItem(ls_test_itm_key) == String(ls_test_val))
                                    {
                                        return true;
                                    }
                                else
                                    {
                                        return false;
                                    };

                                localStorage.removeItem(ls_test_itm_key);
                            }
                        catch (exception)
                            {
                                return false;
                            };
                    }
                else
                    {
                        return false;
                    };
            };
    };

/* Conditional Function checks a web browser for 'local storage' support. [END] */

/* Conditional Function checks a web browser for 'web storage' support. [BEGIN] */

/* Prerequisites: 'isSessStorageAllowed()', 'isLclStorageAllowed()' */

if (typeof isWebStorageAllowed !== 'function')
    {
        function isWebStorageAllowed()
            {
                if (isSessStorageAllowed() === true && isLclStorageAllowed() === true)
                    {
                        return true;
                    }
                else
                    {
                        return false;
                    };
            };
    };

/* Conditional Function checks a web browser for 'web storage' support. [END] */
James Anderson Jr.
  • 760
  • 1
  • 8
  • 26