Javascript 检查 sessionStorage 支持的最优雅方式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7192405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:17:05  来源:igfitidea点击:

Most elegant way to check sessionStorage support?

javascript

提问by user900973

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

我有一个 cookie 检查器函数,它在 var 'cookie1' 中存储一个值变量。还有一个 sessionStorage 存储 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?

但是 IE6 和 IE7 不支持 sessionStorage。所以它会抛出一个错误并破坏整个脚本。我可以做这样的事情,但这绝对不优雅。解决这个问题的最优雅的方法是什么?

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
        }
}

采纳答案by Matt

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

回答by Sergey Romanov

if(typeof(sessionStorage) == 'undefined')
{
    sessionStorage = {
        getItem: function(){},
        setItem: function(){},
        clear: function(){},
        removeItem: function(){}
    };
}

And now use as usual. It will always return NULL

现在照常使用。它将始终返回 NULL

But I would consider this script

但我会考虑这个脚本

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

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

This will enable sessionStorage in every browser.

这将在每个浏览器中启用 sessionStorage。

回答by Tarik

function checkSessionStorage()
{
   return window.sessionStorage;
}

If it is undefinedthen sessionStorageis not supported.

如果它是undefined那么sessionStorage不支持。

回答by Ravi

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

我会使用 try/catch 来检查浏览器是否支持 sessionStorage。

function isSessionStorageSupported() {
    var storage = window.sessionStorage;
    try {
      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
}

回答by James Anderson Jr.

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.

我知道我参加聚会有点晚了,但是我已经编写了一些有用的函数并将其放入名为“manage_storage.js”的文件中。我希望它们对你们有用,因为它们对我很有帮助。

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] */

回答by Saint Billios

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

你可以尝试这样的事情:它的作用是如果浏览器不支持 sessionStorage,它会清除会话。

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