programing

HTML5 로컬 스토리지 대체 솔루션

closeapi 2023. 8. 9. 20:45
반응형

HTML5 로컬 스토리지 대체 솔루션

한 코드를 localStorage기본 지원이 없는 브라우저에서.

기본적으로 다음을 사용하여 사이트를 코딩하고 싶습니다.localStorage데이터를 저장하고 기본적으로 지원하지 않는 브라우저에서 계속 작동합니다.이것은 라이브러리가 다음과 같은 경우를 감지한다는 것을 의미합니다.window.localStorage존재하며 존재하는 경우 사용합니다.존재하지 않는 경우 로컬 스토리지에 대한 일종의 대체 방법을 만들 수 있습니다. 이 방법은 다음과 같습니다.window.localStorage네임스페이스입니다.

지금까지 저는 다음과 같은 솔루션을 찾았습니다.

  1. 간단한 세션스토리지 구현.
  2. 쿠키를 사용하는 구현(이 아이디어에 만족하지 않음).
  3. Dojo의 dojox.스토리지, 하지만 그것은 그것만의 것이지, 실제로는 폴백이 아닙니다.

플래시와 Silverlight를 로컬 스토리지에도 사용할 수 있다는 것은 알고 있지만 표준 HTML5 로컬 스토리지의 대체품으로 사용하는 것에 대해서는 아직 아무것도 찾지 못했습니다.아마도 구글 기어스도 이 기능을 가지고 있습니까?

찾은 관련 라이브러리, 리소스 또는 코드 조각을 공유하십시오!저는 특히 순수한 자바스크립트나 jquery 기반 솔루션에 관심이 있지만, 그럴 가능성은 낮다고 생각합니다.

순수 JS 기반 단순 로컬 스토리지 폴리필:

데모: 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>​

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

지속 사용JS(github 저장소) - 클라이언트 측 스토리지를 코드에 대해 원활하고 투명하게 처리합니다.단일 API를 사용하여 다음 백엔드에 대한 지원을 받을 수 있습니다.

  • flash: 플래시 8 영구 스토리지.
  • gears: Google Gears 기반 영구 스토리지.
  • 로컬 스토리지: HTML5 초안 스토리지.
  • whatwg_db: HTML5 초안 데이터베이스 스토리지.
  • 글로벌 스토리지: HTML5 초안 스토리지(이전 사양).
  • 즉, Internet Explorer 사용자 데이터 동작입니다.
  • cookie: 쿠키 기반 영구 저장소.

예를 들어 쿠키를 사용하지 않으려는 경우 이 중 하나를 사용하지 않도록 설정할 수 있습니다.이 라이브러리를 사용하면 IE 5.5+, Firefox 2.0+, Safari 3.1+ 및 Chrome에서 기본 클라이언트 측 스토리지 지원을 받을 수 있으며 브라우저에 Flash 또는 Gears가 있는 경우 플러그인 지원을 받을 수 있습니다.쿠키를 사용하도록 설정하면 모든 작업이 수행됩니다(단, 4KB로 제한됨).

모데니즈르 위키에서 폴리필 페이지를 본 적이 있습니까?

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

이 페이지에서 웹 스토리지 섹션을 찾으면 10개의 잠재적인 솔루션(2011년 7월 기준)을 볼 수 있습니다.

행운을 빌어요! 마크

아래는 모든 코드를 로컬 범위 내에서 캡슐화한 Aamir Afridi 응답의 정리된 버전입니다.

로▁arences▁▁create다▁global를 생성하는 참조를 제거했습니다.ret이며 저장된 분석을 수및 또 " 짓 " 거 " 문 " 자 " 구 의 " 니 분 제 " 습 다 했 " 거 을 " 내의 했습니다.BrowserStorage.get()메서드. 문자열 "true" 또는 "false"를 실제로 저장하려고 할 경우 문제가 발생할 수 있습니다.

로컬 스토리지 API는 문자열 값만 지원하므로 JSON 문자열로 해당 데이터를 인코딩하여 JavaScript 변수 데이터를 저장/인코딩할 수 있습니다. JSON 문자열은 https://github.com/douglascrockford/JSON-js 과 같은 JSON 인코딩/인코딩 라이브러리를 사용하여 디코딩할 수 있습니다.

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

저는 개인적으로 앰프를 더 좋아합니다.과거에 이 솔루션은 저에게 매우 효과적이었으며 모든 로컬 스토리지 요구사항에 적합하도록 권장했습니다.

IE 5+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+를 지원하며 스토리지 크로스 브라우저를 처리할 수 있는 일관된 API 제공

store.js는 다른 브라우저에서 userData 및 IE와 localStorage를 사용합니다.

  • 너무 복잡한 작업을 시도하지 않습니다.

  • 쿠키도, 플래시도, jQuery도 필요 없습니다.

  • API를 정리합니다.

  • 5kb 압축

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

DOM 저장소의 MDN 페이지에서는 쿠키를 사용하는 몇 가지 해결 방법을 제공합니다.

잔디 의자도 좋은 대안인 것 같습니다.

잔디 의자는 더 작고 밖에 있는 것을 제외하고는 소파와 같습니다.가볍고 적응력이 뛰어나고 단순하며 우아한 지속성 솔루션이 필요한 html5 모바일 앱에 적합합니다.

  • 수집품들. 잔디 의자 인스턴스는 정말로 단지 물건들의 배열일 뿐입니다.
  • 적응 지속성기본 저장소는 일관된 인터페이스 뒤에 추상화됩니다.
  • 플러그인 가능한 수집 동작입니다.때때로 우리는 수집 도우미가 필요하지만 항상은 아닙니다.

Gears를 대체품으로 사용하는 실제 스토리지가 있습니다.

언급URL : https://stackoverflow.com/questions/4692245/html5-local-storage-fallback-solutions

반응형