HTML5 로컬 스토리지 대체 솔루션
localStorage네이티브 지원이없는 브라우저에서 시뮬레이트 할 수있는 자바 스크립트 라이브러리 및 코드를 찾고 있습니다 .
기본적으로 localStorage데이터를 저장하는 데 사용하여 내 사이트를 코딩하고 기본적으로 지원하지 않는 브라우저에서 작동한다는 것을 알고 싶습니다. 이는 라이브러리가 window.localStorage존재 하는지 감지하고 존재하는 경우이를 사용함을 의미합니다. 존재하지 않으면 window.localStorage네임 스페이스 에서 자체 구현을 작성하여 일종의 로컬 스토리지 폴백 메소드를 작성 합니다.
지금까지 이러한 솔루션을 찾았습니다.
- 간단한 sessionStorage 구현.
- 쿠키를 사용 하는 구현 (이 아이디어에 감격하지 않음).
- Dojo의 dojox.storage 이지만 실제로는 폴 백이 아니라 자체입니다.
Flash 및 Silverlight는 로컬 저장소에도 사용할 수 있지만 표준 HTML5 localStorage의 대체물로 사용하는 데 대한 내용은 없습니다. Google Gears에도이 기능이 있습니까?
찾은 관련 라이브러리, 리소스 또는 코드 스 니펫을 공유하십시오! 나는 순수한 자바 스크립트 또는 jquery 기반 솔루션에 특히 관심이 있지만 그럴 것 같지는 않습니다.
PersistJS ( github repository )를 사용하여 클라이언트 측 스토리지를 코드에 완벽하고 투명하게 처리합니다. 단일 API를 사용하고 다음 백엔드를 지원합니다.
- 플래시 : 플래시 8 영구 저장소.
- 기어 : Google Gears 기반 영구 저장소.
- localstorage : HTML5 초안 저장소.
- whatwg_db : HTML5 임시 데이터베이스 스토리지.
- globalstorage : HTML5 초안 저장 (이전 사양).
- 즉, Internet Explorer 사용자 데이터 동작.
- 쿠키 : 쿠키 기반 영구 저장소.
예를 들어 쿠키를 사용하지 않으려는 경우 이러한 기능을 비활성화 할 수 있습니다. 이 라이브러리를 사용하면 IE 5.5 이상, Firefox 2.0 이상, Safari 3.1 이상 및 Chrome에서 기본 클라이언트 측 스토리지 지원을받을 수 있습니다. 브라우저에 Flash 또는 Gears가있는 경우 플러그인 지원. 쿠키를 활성화하면 모든 쿠키가 작동하지만 4kB로 제한됩니다.
순수한 JS 기반의 간단한 localStorage 폴리 필 :
데모 : 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);
}
}
}
Modernizr 위키에서 polyfill 페이지를 보셨습니까?
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).
good luck! Mark
Below is a tidied up version of Aamir Afridi's response that keeps all its code encapsulated within the local scope.
I've removed references that create a global ret variable 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".
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
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);
}
};
})();
I personally prefer amplify.js. It has worked really well for me in the past and I recommended it for all local storage needs.
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
store.js uses userData and IE and localStorage on other browsers.
It does not try to do anything too complex
No cookies, no flash, no jQuery needed.
Clean API.
5 kb compressed
https://github.com/marcuswestin/store.js
The MDN page for DOM storage gives several workarounds that use cookies.
Lawnchair seems 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.
There is realstorage, which uses Gears as a fallback.
참고URL : https://stackoverflow.com/questions/4692245/html5-local-storage-fallback-solutions
'IT박스' 카테고리의 다른 글
| 팬더 열에 특정 값이 포함되어 있는지 확인하는 방법 (0) | 2020.08.04 |
|---|---|
| Team Foundation 작업 항목 유형의 제품 백 로그 항목과 기능의 차이점 (0) | 2020.08.04 |
| JS를 사용하여 옵션 목록을 표시하기 위해 HTML 선택을 열 수 있습니까? (0) | 2020.08.04 |
| 여러 테이블에 대한 외래 키 (0) | 2020.08.04 |
| 트래픽이 많은 시나리오에서 ASP.NET에서 ThreadPool.QueueUserWorkItem 사용 (0) | 2020.08.04 |