Javascript HTML5 本地存储回退解决方案

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4692245/
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-23 13:39:27  来源:igfitidea点击:

HTML5 Local Storage fallback solutions

javascriptjqueryflashhtmllocal-storage

提问by Tauren

I'm looking for javascript libraries and code that can simulate localStorageon browsers that do not have native support.

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

Basically, I'd like to code my site using localStorageto store data and know that it will still work on browsers that don't natively support it. This would mean a library would detect if window.localStorageexists and use it if it does. If it doesn't exist, then it would create some sort of fallback method of local storage, by creating its own implementation in the window.localStoragenamespace.

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

So far, I've found these solutions:

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

  1. Simple sessionStorageimplementation.
  2. An implementation that uses cookies(not thrilled with this idea).
  3. Dojo's dojox.storage, but it is it's own thing, not really a fallback.
  1. 简单的sessionStorage实现。
  2. 使用 cookie的实现(对这个想法并不感兴趣)。
  3. Dojo 的dojox.storage,但它是它自己的东西,并不是真正的后备。

I understand that Flash and Silverlight can be used for local storage as well, but haven't found anything on using them as a fallback for standard HTML5 localStorage. Perhaps Google Gears has this capability too?

我知道 Flash 和 Silverlight 也可用于本地存储,但还没有发现将它们用作标准 HTML5 localStorage 的后备。也许 Google Gears 也有这个功能?

Please share any related libraries, resources, or code snippets that you've found! I'd be especially interested in pure javascript or jquery-based solutions, but am guessing that is unlikely.

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

采纳答案by josh3736

I use PersistJS(github repository), which handles client-side storage seamlessly and transparently to your code. You use a single API and get support for the following backends:

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

  • flash: Flash 8 persistent storage.
  • gears: Google Gears-based persistent storage.
  • localstorage: HTML5 draft storage.
  • whatwg_db: HTML5 draft database storage.
  • globalstorage: HTML5 draft storage (old spec).
  • ie: Internet Explorer userdata behaviors.
  • cookie: Cookie-based persistent storage.
  • flash:Flash 8 持久化存储。
  • gears:基于 Google Gears 的持久存储。
  • localstorage:HTML5 草稿存储。
  • whatwg_db:HTML5 草稿数据库存储。
  • globalstorage:HTML5 草稿存储(旧规范)。
  • 即:Internet Explorer 用户数据行为。
  • cookie:基于 cookie 的持久存储。

Any of those can be disabled—if, for example, you don't want to use cookies. With this library, you'll get native client-side storage support in IE 5.5+, Firefox 2.0+, Safari 3.1+, and Chrome; and plugin-assisted support if the browser has Flash or Gears. If you enable cookies, it will work in everything (but will be limited to 4 kB).

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

回答by Aamir Afridi

Pure JS based simple localStorage polyfill:

基于纯 JS 的简单 localStorage polyfill:

Demo: http://jsfiddle.net/aamir/S4X35/

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

HTML:

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

JS:

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);
        }
    }
}?

回答by Mark Lummus

have you seen the polyfill page on the Modernizr wiki?

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

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

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

look for the webstorage section on that page and you will see 10 potential solutions (as of July 2011).

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

good luck! Mark

祝你好运!标记

回答by Steven

Below is a tidied up version of Aamir Afridi's response that keeps all its code encapsulated within the local scope.

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

I've removed references that create a global retvariable and also removed the parsing of stored "true" and "false" strings into boolean values within the BrowserStorage.get()method, which could cause issues if one is trying to in fact store the strings "true" or "false".

我删除了创建全局ret变量的引用,并删除了将存储的“true”和“false”字符串解析为BrowserStorage.get()方法中的布尔值,如果试图实际存储字符串“true”或“错误的”。

Since the local storage API only supports string values, one could still store/retrieve JavaScript variable data along with their appropriate data types by encoding said data into a JSON string, which can then be decoded using a JSON encode/decode library such as https://github.com/douglascrockford/JSON-js

由于本地存储 API 仅支持字符串值,因此仍然可以通过将 JavaScript 变量数据编码为 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);
        }
    };
})();

回答by raidfive

I personally prefer amplify.js. It has worked really well for me in the past and I recommended it for all local storage needs.

我个人更喜欢amplify.js。过去它对我来说效果很好,我推荐它满足所有本地存储需求。

supports IE 5+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ and provides a consistent API to handle storage cross-browser

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

回答by Mikko Ohtamaa

store.js uses userData and IE and localStorage on other browsers.

store.js 在其他浏览器上使用 userData 和 IE 以及 localStorage。

  • It does not try to do anything too complex

  • No cookies, no flash, no jQuery needed.

  • Clean API.

  • 5 kb compressed

  • 它不会尝试做任何过于复杂的事情

  • 没有cookies,没有flash,不需要jQuery。

  • 干净的 API。

  • 5 kb 压缩

https://github.com/marcuswestin/store.js

https://github.com/marcuswestin/store.js

回答by j0k

Lawnchairseems to be a good alternative too

草坪椅似乎也是一个不错的选择

a lawnchair is sorta like a couch except smaller and outside. perfect for html5 mobile apps that need a lightweight, adaptive, simple and elegant persistence solution.

  • collections. a lawnchair instance is really just an array of objects.
  • adaptive persistence. the underlying store is abstracted behind a consistent interface.
  • pluggable collection behavior. sometimes we need collection helpers but not always.

草坪椅有点像沙发,除了更小和更外面。非常适合需要轻量级、自适应、简单而优雅的持久性解决方案的 html5 移动应用程序。

  • 集合。一个草坪椅实例实际上只是一个对象数组。
  • 适应性持久性。底层存储被抽象在一个一致的接口后面。
  • 可插拔的收集行为。有时我们需要收集助手,但并非总是如此。

回答by alex

The MDN page for DOM storagegives several workarounds that use cookies.

DOM 存储MDN 页面提供了几种使用 cookie 的解决方法。

回答by Gaurav

There is realstorage, which uses Gears as a fallback.

realstorage,它使用 Gears 作为后备。