HTML5本地存储后备解决方案

Tau*_*ren 113 javascript flash jquery html5 local-storage

我正在寻找可以localStorage在没有本机支持的浏览器上模拟的JavaScript库和代码.

基本上,我想使用localStorage存储数据编码我的网站,并知道它仍然适用于本机不支持它的浏览器.这意味着库将检测是否window.localStorage存在并且如果存在则使用它.如果它不存在,那么它将通过在window.localStorage命名空间中创建自己的实现来创建某种本地存储的回退方法.

到目前为止,我已经找到了这些解决方案:

  1. 简单的sessionStorage实现.
  2. 使用cookie的实现(对此想法不感兴趣).
  3. Dojo的dojox.storage,但这是它自己的事情,而不是真正的后备.

我知道Flash和Silverlight也可以用于本地存储,但是没有找到任何使用它们作为标准HTML5 localStorage的后备.也许谷歌Gears也有这个功能?

请分享您找到的任何相关库,资源或代码段!我对纯javascript或基于jquery的解决方案特别感兴趣,但我猜这不太可能.

Aam*_*idi 59

纯JS基于简单的localStorage polyfill:

演示:http://jsfiddle.net/aamir/S4X35/

HTML:

<a href='#' onclick="store.set('foo','bar')">set key: foo, with value: bar</a><br/>
<a href='#' onclick="alert(store.get('foo'))">get key: foo</a><br/>
<a href='#' onclick="store.del('foo')">delete key: foo</a>?
Run Code Online (Sandbox Code Playgroud)

JS:

window.store = {
    localStoreSupport: function() {
        try {
            return 'localStorage' in window && window['localStorage'] !== null;
        } catch (e) {
            return false;
        }
    },
    set: function(name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else {
            var expires = "";
        }
        if( this.localStoreSupport() ) {
            localStorage.setItem(name, value);
        }
        else {
            document.cookie = name+"="+value+expires+"; path=/";
        }
    },
    get: function(name) {
        if( this.localStoreSupport() ) {
            var ret = localStorage.getItem(name);
            //console.log(typeof ret);
            switch (ret) {
              case 'true': 
                  return true;
              case 'false':
                  return false;
              default:
                  return ret;
            }
        }
        else {
            // cookie fallback
            /*
             * after adding a cookie like
             * >> document.cookie = "bar=test; expires=Thu, 14 Jun 2018 13:05:38 GMT; path=/"
             * the value of document.cookie may look like
             * >> "foo=value; bar=test"
             */
            var nameEQ = name + "=";  // what we are looking for
            var ca = document.cookie.split(';');  // split into separate cookies
            for(var i=0;i < ca.length;i++) {
                var c = ca[i];  // the current cookie
                while (c.charAt(0)==' ') c = c.substring(1,c.length);  // remove leading spaces
                if (c.indexOf(nameEQ) == 0) {  // if it is the searched cookie
                    var ret = c.substring(nameEQ.length,c.length);
                    // making "true" and "false" a boolean again.
                    switch (ret) {
                      case 'true':
                          return true;
                      case 'false':
                          return false;
                      default:
                          return ret;
                    }
                }
            }
            return null; // no cookie found
        }
    },
    del: function(name) {
        if( this.localStoreSupport() ) {
            localStorage.removeItem(name);
        }
        else {
            this.set(name,"",-1);
        }
    }
}?
Run Code Online (Sandbox Code Playgroud)

  • 为什么这不被认可!?谢啦! (4认同)
  • :) - 我不喜欢为我需要的东西添加一个完整的lib. (3认同)
  • 只是想指出,当你允许在cookie上设置过期时,localStorage永远不会过期.如果您正在寻找到期的东西,这可能会导致一些问题.包括在localstorage中添加到期日期,然后进行日期比较以查看它是否仍然适用可能是有益的.当然,我也会争辩说,如果你需要过期,你应该只使用一个cookie.但我认为这个脚本要么不允许过期,要么允许两者,而不是像目前那样不一致. (3认同)
  • 是否允许JavaScript在本地定义`var expires`然后在其他范围内定义用户?在函数`set`中 (2认同)

jos*_*736 54

我使用PersistJS(github存储库),它可以无缝且透明地处理客户端存储.您使用单个API并获得对以下后端的支持:

  • flash:Flash 8持久存储.
  • 齿轮:基于Google Gears的持久存储.
  • localstorage:HTML5草稿存储.
  • whatwg_db:HTML5草案数据库存储.
  • globalstorage:HTML5草案存储(旧规范).
  • 即:Internet Explorer用户数据行为.
  • cookie:基于Cookie的持久存储.

任何这些都可以被禁用 - 例如,如果您不想使用cookie.使用此库,您将获得IE 5.5 +,Firefox 2.0 +,Safari 3.1+和Chrome中的本机客户端存储支持; 如果浏览器有Flash或Gears,则提供插件辅助支持.如果启用cookie,它将适用于所有内容(但限制为4 kB).

  • PersistJS仍然受支持吗?我想知道它是如何解决浏览器升级和所选存储方法改变的问题(比如本地存储变得可用).旧位置是否无法访问? (9认同)
  • 它至少看起来不再像是在积极开发中了. (2认同)

Mar*_*mus 19

你看过Modernizr wiki上的polyfill页面吗?

https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills

查找该页面上的webstorage部分,您将看到10个可能的解决方案(截至2011年7月).

祝好运!标记


Ste*_*ven 14

下面是Aamir Afridi的响应的整理版本,它将所有代码封装在本地范围内.

我删除了创建全局ret变量的引用,并删除了将存储的"true"和"false"字符串解析为BrowserStorage.get()方法中的布尔值,这可能会导致问题,如果实际上存储字符串"true"或"假".

由于本地存储API仅支持字符串值,因此可以通过将所述数据编码为JSON字符串来存储/检索JavaScript变量数据及其适当的数据类型,然后可以使用JSON编码/解码库(如https)对其进行解码: //github.com/douglascrockford/JSON-js

var BrowserStorage = (function() {
    /**
     * Whether the current browser supports local storage as a way of storing data
     * @var {Boolean}
     */
    var _hasLocalStorageSupport = (function() {
        try {
            return 'localStorage' in window && window['localStorage'] !== null;
        } catch (e) {
            return false;
        }
    })();

    /**
     * @param {String} name The name of the property to read from this document's cookies
     * @return {?String} The specified cookie property's value (or null if it has not been set)
     */
    var _readCookie = function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }

        return null;
    };

    /**
     * @param {String} name The name of the property to set by writing to a cookie
     * @param {String} value The value to use when setting the specified property
     * @param {int} [days] The number of days until the storage of this item expires
     */
    var _writeCookie = function(name, value, days) {
        var expiration = (function() {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days*24*60*60*1000));
                return "; expires=" + date.toGMTString();
            }
            else {
                return "";
            }
        })();

        document.cookie = name + "=" + value + expiration + "; path=/";
    };

    return {
        /**
         * @param {String} name The name of the property to set
         * @param {String} value The value to use when setting the specified property
         * @param {int} [days] The number of days until the storage of this item expires (if storage of the provided item must fallback to using cookies)
         */
        set: function(name, value, days) {
            _hasLocalStorageSupport
                ? localStorage.setItem(name, value)
                : _writeCookie(name, value, days);
        },

        /**
         * @param {String} name The name of the value to retrieve
         * @return {?String} The value of the 
         */
        get: function(name) {
            return _hasLocalStorageSupport
                ? localStorage.getItem(name) 
                : _readCookie(name);
        },

        /**
         * @param {String} name The name of the value to delete/remove from storage
         */
        remove: function(name) {
            _hasLocalStorageSupport
                ? localStorage.removeItem(name)
                : this.set(name, "", -1);
        }
    };
})();
Run Code Online (Sandbox Code Playgroud)


rai*_*ive 10

我个人更喜欢amplify.js.它在过去对我来说非常好用,我建议它满足所有本地存储需求.

支持IE 5 +,Firefox 2 +,Safari 4 +,Chrome,Opera 10.5 +,iPhone 2 +,Android 2+,并提供一致的API来处理存储跨浏览器