Sie sind auf Seite 1von 5

5/2/2015

jStoragesimpleJavaScriptplugintostoredatalocally

jStoragestoredatalocallywithJavaScript
jStorageisacrossbrowserkeyvaluestoredatabasetostoredatalocallyinthebrowserjStoragesupportsallmajor
browsers,bothindesktop(yesevenInternetExplorer6)andinmobile.
AdditionallyjStorageislibraryagnostic,itworkswellwithanyotherJavaScriptlibraryonthesamewebpage,beitjQuery,
Prototype,MooToolsorsomethingelse.Thoughyoustillneedtohaveeitherathirdpartylibrary(Prototype,MooTools)or
JSON2onthepagetosupportolderIEversions.
jStoragesupportsstoringStrings,Numbers,JavaScriptobjects,ArraysandevennativeXMLnodes.jStoragealsosupports
settingTTLvaluesforautoexpiringstoredkeysandbestofallnotifyingothertabs/windowswhenakeyhasbeenchanged
orpublishing/subscribingtoeventsfromthesameoranothertab/window,whichmakesjStoragealsoalocalPubSubplatform
forwebapplications.
jStorageisprettysmall,about7kBwhenminifiedand4kBgzipped.

Donate
SupportjStoragedevelopment

Index
1.
2.
3.
4.
5.
6.
7.
8.
9.

Basics
Download
Interactivetest
Browsersupport
Usage
Functionreference
Usageexample
Issues
ContactandCopyright

1.Basics
jStoragemakesuseofHTML5localstoragewhereavailableanduserDatabehaviorinInternetExplorerolderversions.
Currentavailability:jStoragesupportsallmajorbrowsersInternetExplorer6+,Firefox2+,Safari4+,Chrome4+,Opera
10.50+
Ifthebrowserdoesn'tsupportdatacaching,thennoexceptionsareraisedjStoragecanstillbeusedbythescriptbut
nothingisactuallystored.
jStorageisreallysmall,justabout7kBwhenminified(4kBwhengzipped)!
http://www.jstorage.info/#basics

1/5

5/2/2015

jStoragesimpleJavaScriptplugintostoredatalocally

2.Download
jStoragecanbedownloadedatgithub(directdownloadlink)

3.Interactivetest
Addsomevaluesandrefreshthepageifyourbrowsersupportsstoringlocaldata,thenthevaluesshouldsurvivethepage
refresh.
KEY

VALUE

ADD

Clicking"GET"alertsthevalueforprovidedkeywiththemethod$.jStorage.get(key)

GET

Clearallsaveddata

FLUSH

4.Browsersupport
Storagesupport

Survivesbrowser
restart

Survivesbrowser
crash

Storagesize

Chrome4

5MB

Firefox3.6

5MB

Firefox3

5MB

Firefox2

5MB

IE8

10MB

IE7

128kB

IE6

128kB

Opera10.50

5MB

Opera10.10

Safari4

5MB

IphoneSafari

5MB

Safari3

Browser

N/A

N/A

N/A

N/A

N/A

N/A

5.Usage
jStoragerequiresPrototype,MooToolsorjQuery+jQueryJSONorJSON2.Eitherway,thesyntaxstaysthesame.
SimplesetuptosupportjStoragewithJSON2
<scriptsrc="//cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>
<scriptsrc="https://raw.github.com/andris9/jStorage/master/jstorage.js"></script>
<script>/*$.jStorageisnowavailable*/</script>
SetupwithjQuery2
<scriptsrc="//cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<scriptsrc="https://raw.github.com/andris9/jStorage/master/jstorage.js"></script>
<script>/*$.jStorageisnowavailable*/</script>
http://www.jstorage.info/#basics

2/5

5/2/2015

jStoragesimpleJavaScriptplugintostoredatalocally

6.Functionreference
set(key,value[,options])
$.jStorage.set(key,value,options)
Savesavaluetolocalstorage.keyneedstobestringotherwiseanexceptionisthrown.valuecanbeanyJSONeablevalue,
includingobjectsandarraysoraXMLnode.
CurrentlyXMLnodescan'tbenestedinsideotherobjects:$.jStorage.set("xml",xml_node)isOKbut$.jStorage.set("xml",
{xml:xml_node})isnot.
Optionsisanoptionaloptionsobject.Currentlyonlyavailableoptionisoptions.TTLwhichcanbeusedtosettheTTLvalue
tothekey($.jStorage.set(key,value,{TTL:1000});).NBifnoTTLoptionvaluehasbeenset,anycurrentlyused
TTLvalueforthekeywillberemoved.

get(key[,default])
value=$.jStorage.get(key)
value=$.jStorage.get(key,"defaultvalue")

getretrievesthevalueifkeyexists,ordefaultifitdoesn't.keyneedstobestringotherwiseanexceptionisthrown.default
canbeanyvalue.

deleteKey(key)
$.jStorage.deleteKey(key)
Removesakeyfromthestorage.keyneedstobestringotherwiseanexceptionisthrown.

setTTL(key,ttl)
$.jStorage.set("mykey","keyvalue");
$.jStorage.setTTL("mykey",3000);//expiresin3seconds
SetsaTTL(inmilliseconds)foranexistingkey.Use0ornegativevaluetoclearTTL.

getTTL(key)
ttl=$.jStorage.getTTL("mykey");//TTLinmillisecondsor0
GetsremainingTTL(inmilliseconds)forakeyor0ifnotTTLhasbeenset.

flush()
$.jStorage.flush()
Clearsthecache.

index()
$.jStorage.index()
Returnsallthekeyscurrentlyinuseasanarray.
varindex=$.jStorage.index();
console.log(index);//["key1","key2","key3"]

storageSize()
$.jStorage.storageSize()
Returnsthesizeofthestoreddatainbytes

currentBackend()
http://www.jstorage.info/#basics

3/5

5/2/2015

jStoragesimpleJavaScriptplugintostoredatalocally

$.jStorage.currentBackend()
Returnsthestorageenginecurrentlyinuseorfalseifnone

reInit()
$.jStorage.reInit()
Reloadsthedatafrombrowserstorage

storageAvailable()
$.jStorage.storageAvailable()
Returnstrueifstorageisavailable

subscribe(channel,callback)
$.jStorage.subscribe("ch1",function(channel,payload){
console.log(payload+"from"+channel);
});
SubscribestoaPublish/Subscribechannel)

publish(channel,payload)
$.jStorage.publish("ch1","data");
PublishespayloadtoaPublish/Subscribechannel

listenKeyChange(key,callback)
$.jStorage.listenKeyChange("mykey",function(key,action){
console.log(key+"hasbeen"+action);
});
Listensforupdatesforselectedkey.NB!evenupdatesmadeinotherwindows/tabsarereflected,sothisfeaturecanalsobe
usedforsomekindofpublish/subscribeservice.

stopListening(key[,callback])
$.jStorage.stopListening("mykey");//cancelalllistenersfor"mykey"change
Stopslisteningforkeychange.Ifcallbackisset,onlytheusedcallbackwillbecleared,otherwisealllistenerswillbe
dropped.

7.Usageexample
jQuery
jQuerydoesn'tcomewithbuiltinJSONencoder/decodersoifyouneedtosupportIE6/IE7youshouldincludeoneyourselt
likeintheexample
<scriptsrc="//cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>
<scriptsrc="//code.jquery.com/jquery1.9.1.min.js"></script>
<scriptsrc="jstorage.js"></script>
<script>
//Checkif"key"existsinthestorage
varvalue=$.jStorage.get("key");
if(!value){
//ifnotloadthedatafromtheserver
value=load_data_from_server()
//andsaveit
$.jStorage.set("key",value);
http://www.jstorage.info/#basics

4/5

5/2/2015

jStoragesimpleJavaScriptplugintostoredatalocally

}
</script>

Prototype
<scriptsrc="//ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script>
<scriptsrc="jstorage.js"></script>
<script>
//Checkif"key"existsinthestorage
varvalue=$.jStorage.get("key");
if(!value){
//ifnotloadthedatafromtheserver
value=load_data_from_server()
//andsaveit
$.jStorage.set("key",value);
}
</script>

8.Issues
WhywouldyouwanttousejStoragewhencookiesworkalreadyineverybrowser?
CookiesarenotmeanttosavelargequantitiesofdatalocallytheyaremeanttopassaroundIDvaluestokeeptrack
ofusers.InternetExplorerallowstouseupto20cookiesperdomainwiththepayloadof4kBpercookie.Itisn'tvery
much,especiallyconsideringtheneedtochunklargerdataintosmallerbits.Thefactthatthedata(max.80kB)is
senttotheserverwith*every*calldoesn'tsoundmuchofagoodideaeither.

9.ContactandCopyright
20102012AndrisReinman,andris.reinman@gmail.com
jStorageislicensedunderUnlicense,sobasicallyyoucandowhateveryouwanttodowithit.

http://www.jstorage.info/#basics

5/5

Das könnte Ihnen auch gefallen