判断是否支持Web Storage

发布于 2024-12-18 11:42:32 字数 403 浏览 2 评论 0原文

我需要验证 Web Storage API 是否受支持且可用(它可能由于安全问题而被禁用)。

因此,我认为检查 sessionStorage 或 localStorage 类型是否已定义就足够了:

if (typeof sessionStorage != 'undefined')
{
    alert('sessionStorage available');
}
else
{
    alert('sessionStorage not available');
}

但是,我想知道该类型是否可能存在,但无论如何我都无法使用 Web Storage API。

评论: 我知道如果禁用cookie并且访问sessionStorage或localStorage,Firefox会抛出安全错误。

I need to verify that Web Storage API is supported and available (it may be disabled due to security issues).

So, I thought it would suffice to check whether the type sessionStorage or localStorage is defined or not:

if (typeof sessionStorage != 'undefined')
{
    alert('sessionStorage available');
}
else
{
    alert('sessionStorage not available');
}

However, I was wondering if it could be possible that the type exists, but I wouldn't been able to use the Web Storage API anyway.

Remarks:
I know Firefox will throw a security error if cookies are disabled and sessionStorage or localStorage are accessed.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

清泪尽 2024-12-25 11:42:32

为什么不使用 Modernizr 库来检测是否支持本地存储?浏览器之间的任何差异都会为您处理,然后您可以使用如下代码:

if (Modernizr.localstorage) {
    // browser supports local storage
} else {
    // browser doesn't support local storage
}

Why don't you use the Modernizr library to detect if local storage is supported or not? Any differences between browers will be taken care of for you, you can then just use code like this:

if (Modernizr.localstorage) {
    // browser supports local storage
} else {
    // browser doesn't support local storage
}
还如梦归 2024-12-25 11:42:32

我认为你的原始代码走在正确的轨道上,不需要让它变得太花哨。

在代码中使用 KISS 原则,无需任何其他依赖项:

var storageEnabled = function() {
    try {
        sessionStorage.setItem('test-key','test-value');
        if (sessionStorage.getItem('test-key') == 'test-value'){
            return true;
        }
    } catch (e) {};
    return false;
};

alert(storageEnabled() ? 'sessionStorage available' : 'sessionStorage not available');

I think you're on the right track with your original code, no need to make this too fancy.

Using the KISS principle with no additional dependencies in your code:

var storageEnabled = function() {
    try {
        sessionStorage.setItem('test-key','test-value');
        if (sessionStorage.getItem('test-key') == 'test-value'){
            return true;
        }
    } catch (e) {};
    return false;
};

alert(storageEnabled() ? 'sessionStorage available' : 'sessionStorage not available');
情域 2024-12-25 11:42:32
try{
    ssSupport = Object.prototype.toString.call( sessionStorage ) === "[object Storage]";
}
catch(e){
    ssSupport = false;
}
try{
    ssSupport = Object.prototype.toString.call( sessionStorage ) === "[object Storage]";
}
catch(e){
    ssSupport = false;
}
这个俗人 2024-12-25 11:42:32

因此,因为 Modernizr.localstorage 分别 Modernizr.sessionstorage 将返回 true,而 Firefox 可能会与禁用的 Cookie(这将导致安全错误)或任何其他专有(意外)一起使用)可能会发生行为:我编写了自己的 webStorageEnabled 函数,该函数似乎工作得很好。

function cookiesEnabled()
{
    // generate a cookie to probe cookie access
    document.cookie = '__cookieprobe=0;path=/';
    return document.cookie.indexOf('__cookieprobe') != -1;
}

function webStorageEnabled()
{
    if (typeof webStorageEnabled.value == 'undefined')
    {
        try
        {
            localStorage.setItem('__webstorageprobe', '');
            localStorage.removeItem('__webstorageprobe');
            webStorageEnabled.value = true;
        }
        catch (e) {
            webStorageEnabled.value = false;
        }
    }

    return webStorageEnabled.value;
}


// conditional

var storage = new function()
{
    if (webStorageEnabled())
    {
        return {
            local:   localStorage,
            session: sessionStorage
        };
    }
    else
    {
        return {
            local: cookiesEnabled() ? function()
            {
                // use cookies here
            }() : null,

            session: function()
            {
                var data = {};

                return {
                    clear: function () {
                        data = {};
                    },

                    getItem: function(key) {
                        return data[key] || null;
                    },

                    key: function(i)
                    {
                        var index = 0;
                        for (var value in data)
                        {
                            if (index == i)
                                return value;
                            ++index;
                        }
                    },

                    removeItem: function(key) {
                        delete data[key];
                    },

                    setItem: function(key, value) {
                        data[key] = value + '';
                    }
                };
            }()
        };
    }
}

希望这对某人也有用。

So, because Modernizr.localstorage respectively Modernizr.sessionstorage will return true while Firefox might be used with disabled Cookies (which will lead into an security error) or any other proprietary (unexpected) behavior could occur: I've written my own webStorageEnabled function which seems to work very well.

function cookiesEnabled()
{
    // generate a cookie to probe cookie access
    document.cookie = '__cookieprobe=0;path=/';
    return document.cookie.indexOf('__cookieprobe') != -1;
}

function webStorageEnabled()
{
    if (typeof webStorageEnabled.value == 'undefined')
    {
        try
        {
            localStorage.setItem('__webstorageprobe', '');
            localStorage.removeItem('__webstorageprobe');
            webStorageEnabled.value = true;
        }
        catch (e) {
            webStorageEnabled.value = false;
        }
    }

    return webStorageEnabled.value;
}


// conditional

var storage = new function()
{
    if (webStorageEnabled())
    {
        return {
            local:   localStorage,
            session: sessionStorage
        };
    }
    else
    {
        return {
            local: cookiesEnabled() ? function()
            {
                // use cookies here
            }() : null,

            session: function()
            {
                var data = {};

                return {
                    clear: function () {
                        data = {};
                    },

                    getItem: function(key) {
                        return data[key] || null;
                    },

                    key: function(i)
                    {
                        var index = 0;
                        for (var value in data)
                        {
                            if (index == i)
                                return value;
                            ++index;
                        }
                    },

                    removeItem: function(key) {
                        delete data[key];
                    },

                    setItem: function(key, value) {
                        data[key] = value + '';
                    }
                };
            }()
        };
    }
}

Hope this will be useful for someone too.

苦行僧 2024-12-25 11:42:32

我的版本(因为 IE 9 运行在 IE 8 以上的 Intranet 站点上已损坏)。

if (typeof (Storage) != "undefined" && !!sessionStorage.getItem) {

}

一个更长的版本,添加了 setObject 以允许存储对象:

var sstorage;

if (typeof (Storage) != "undefined" && !!sessionStorage.getItem) {
    Storage.prototype.setObject = function (key, value) {
        this.setItem(key, JSON.stringify(value));
    };

    Storage.prototype.getObject = function (key) {
        return JSON.parse(this.getItem(key));
    };
    if (typeof sessionStorage.setObject == "function") {
        sstorage = sessionStorage;
    }
    else {
        setupOldBrowser();
    }
}
else {
    setupOldBrowser();
}


function setupOldBrowser() {
    sstorage = {};
    sstorage.setObject = function (key, value) {
        this[key] = JSON.stringify(value);
    };
    sstorage.getObject = function (key) {
        if (typeof this[key] == 'string') {
            return JSON.parse(this[key]);
        }
        else {
            return null;
        }
    };

    sstorage.removeItem = function (key) {
        delete this[key];
    };
}

My version (because IE 9 running in IE 8 more on an intranet site is broken).

if (typeof (Storage) != "undefined" && !!sessionStorage.getItem) {

}

a longer version that adds setObject to allow storing objects:

var sstorage;

if (typeof (Storage) != "undefined" && !!sessionStorage.getItem) {
    Storage.prototype.setObject = function (key, value) {
        this.setItem(key, JSON.stringify(value));
    };

    Storage.prototype.getObject = function (key) {
        return JSON.parse(this.getItem(key));
    };
    if (typeof sessionStorage.setObject == "function") {
        sstorage = sessionStorage;
    }
    else {
        setupOldBrowser();
    }
}
else {
    setupOldBrowser();
}


function setupOldBrowser() {
    sstorage = {};
    sstorage.setObject = function (key, value) {
        this[key] = JSON.stringify(value);
    };
    sstorage.getObject = function (key) {
        if (typeof this[key] == 'string') {
            return JSON.parse(this[key]);
        }
        else {
            return null;
        }
    };

    sstorage.removeItem = function (key) {
        delete this[key];
    };
}
甜妞爱困 2024-12-25 11:42:32

这是我使用会话存储(如果可用)的方法,如果不可用,请使用 cookie。

var setCookie; 
var getCookie;

var sessionStorageSupported = 'sessionStorage' in window 
                                   && window['sessionStorage'] !== null;

if (sessionStorageSupported) {
    setCookie = function (cookieName, value) {
        window.sessionStorage.setItem(cookieName, value);
        return value; //you can introduce try-catch here if required
    };
    getCookie = function (cookieName) {
        return window.sessionStorage.getItem(cookieName);
    };
}
else {
    setCookie = function (cookieName, value) {
        $.cookie(cookieName, value);
        return value; // null if key not present
    };
    getCookie = function(cookieName) {
        console.log("using cookies");
        return $.cookie(cookieName);
    };
}

Here's what I do to use session storage if available if it's not, use cookies..

var setCookie; 
var getCookie;

var sessionStorageSupported = 'sessionStorage' in window 
                                   && window['sessionStorage'] !== null;

if (sessionStorageSupported) {
    setCookie = function (cookieName, value) {
        window.sessionStorage.setItem(cookieName, value);
        return value; //you can introduce try-catch here if required
    };
    getCookie = function (cookieName) {
        return window.sessionStorage.getItem(cookieName);
    };
}
else {
    setCookie = function (cookieName, value) {
        $.cookie(cookieName, value);
        return value; // null if key not present
    };
    getCookie = function(cookieName) {
        console.log("using cookies");
        return $.cookie(cookieName);
    };
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文