jStorage is a simple key/value database to store data on browser side

Related tags

Storage jStorage
Overview

NB!

This project is in a frozen state. No more API changes. Pull requests for bug fixes are welcomed, anything else gets most probably ignored. A bug is something that breaks the application, outdated package file is not a bug.


jStorage

jStorage is a cross-browser key-value store database to store data locally in the browser - jStorage supports all major browsers, both in desktop (yes - even Internet Explorer 6) and in mobile.

Additionally jStorage is library agnostic, it works well with any other JavaScript library on the same webpage, be it jQuery, Prototype, MooTools or something else. Though you still need to have either a third party library (Prototype, MooTools) or JSON2 on the page to support older IE versions.

jStorage supports storing Strings, Numbers, JavaScript objects, Arrays and even native XML nodes which kind of makes it a JSON storage. jStorage also supports setting TTL values for auto expiring stored keys and - best of all - notifying other tabs/windows when a key has been changed, which makes jStorage also a local PubSub platform for web applications.

jStorage is pretty small, about 7kB when minified, 3kB gzipped.

Function reference

set(key, value[, options])

$.jStorage.set(key, value, options)

Saves a value to local storage. key needs to be string otherwise an exception is thrown. value can be any JSONeable value, including objects and arrays or a XML node. Currently XML nodes can't be nested inside other objects: $.jStorage.set("xml", xml_node) is OK but $.jStorage.set("xml", {xml: xml_node}) is not.

Options is an optional options object. Currently only available option is options.TTL which can be used to set the TTL value to the key $.jStorage.set(key, value, {TTL: 1000}). NB - if no TTL option value has been set, any currently used TTL value for the key will be removed.

get(key[, default])

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

get retrieves the value if key exists, or default if it doesn't. key needs to be string otherwise an exception is thrown. default can be any value.

deleteKey(key)

$.jStorage.deleteKey(key)

Removes a key from the storage. key needs to be string otherwise an exception is thrown.

setTTL(key, ttl)

$.jStorage.set("mykey", "keyvalue");
$.jStorage.setTTL("mykey", 3000); // expires in 3 seconds

Sets a TTL (in milliseconds) for an existing key. Use 0 or negative value to clear TTL.

getTTL(key)

ttl = $.jStorage.getTTL("mykey"); // TTL in milliseconds or 0

Gets remaining TTL (in milliseconds) for a key or 0 if not TTL has been set.

flush()

$.jStorage.flush()

Clears the cache.

index()

$.jStorage.index()

Returns all the keys currently in use as an array.

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

storageSize()

$.jStorage.storageSize()

Returns the size of the stored data in bytes

currentBackend()

$.jStorage.currentBackend()

Returns the storage engine currently in use or false if none

reInit()

$.jStorage.reInit()

Reloads the data from browser storage

storageAvailable()

$.jStorage.storageAvailable()

Returns true if storage is available

subscribe(channel, callback)

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

Subscribes to a Publish/Subscribe channel (see demo)

publish(channel, payload)

$.jStorage.publish("ch1", "data");

Publishes payload to a Publish/Subscribe channel (see demo)

listenKeyChange(key, callback)

$.jStorage.listenKeyChange("mykey", function(key, action){
    console.log(key + " has been " + action);
});

Listens for updates for selected key. NB! even updates made in other windows/tabs are reflected, so this feature can also be used for some kind of publish/subscribe service.

If you want to listen for any key change, use "*" as the key name

$.jStorage.listenKeyChange("*", function(key, action){
    console.log(key + " has been " + action);
});

stopListening(key[, callback])

$.jStorage.stopListening("mykey"); // cancel all listeners for "mykey" change

Stops listening for key change. If callback is set, only the used callback will be cleared, otherwise all listeners will be dropped.

Donate

Support jStorage development

Donate to author

Features

jStorage supports the following features:

  • store and retrieve data from browser storage using any JSON compatible data format (+ native XML nodes)
  • set TTL values to stored keys for auto expiring
  • publish and subscribe to cross-window/tab events
  • listen for key changes (update, delete) from the current or any other browser window
  • use any browser since IE6, both in desktop and in mobile

Browser support

Current availability: jStorage supports all major browsers - Internet Explorer 6+, Firefox 2+, Safari 4+, Chrome 4+, Opera 10.50+

If the browser doesn't support data caching, then no exceptions are raised - jStorage can still be used by the script but nothing is actually stored.

License

Unlicense Since version 0.4.7

MIT (versions up to 0.4.6)

Comments
  • iOS5 in Private Browsing mode bombs in bad way

    iOS5 in Private Browsing mode bombs in bad way

    in _load_storage the line: _storage_service.jStorage = "{}";

    throws Error: QUOTA_EXCEEDED_ERR: DOM Exception 22

    This line could be wrapped in a try catch, but I think it would be better to do this sooner when setting the storage engine so that an alternate mechanism could be used.

    opened by elsigh 5
  • $.jStorage.flush() does not persist in Safari 4 on iPad simulator (w/jQuery 1.4.2)

    $.jStorage.flush() does not persist in Safari 4 on iPad simulator (w/jQuery 1.4.2)

    Very odd problem, and everything works fine in every other situation I've tested in. Here's what's happening...

    1. Visit page in Safari in iPad simulator.
    2. Save some data via jStorage.
    3. Refresh page in Safari.
    4. Load data via jStorage.
    5. Clear data via jStorage.flush().
    6. Refresh page in Safari.
    7. Load data via jStorage. The saved data returns.

    The very, very odd thing is that in between steps 5 and 6, if you attempt to load data from storage you can see that the data was successfully cleared. It seems like the iPad version of Safari requires a little extra magic to fully ditch the data on a flush.

    opened by jmhnilbog 5
  • Debian infrastructure

    Debian infrastructure

    Hi!

    I've just packaged jstorage into debian package (and uploaded it into debian repo), so there are some files that can be used to build .deb for the following versions of jstorage.

    If You want we can host them in Your repo, If You don't I will make 'git pull' from time to time :)

    Thanks for Your work!

    opened by unera 4
  • .set() TTL support

    .set() TTL support

    Hey @andris9.

    set() method could really use TTL support.

    I've seen there is a separate setTTL() method but that's just cumbersome to set a TTL after you've set the value. Many server side caching solutions allow you to define ttl when setting a value. It'd be great to add this.

    Here is a proposed syntax:

    $.jStorage.set(key, value, TTL);
    // @var TTL - (optional) expiration time in seconds, after which the value 
    //            is discarded. If omitted or set to 0 the value will never expire.
    
    opened by Thinkscape 4
  • Need to clone objects before storing in storage object

    Need to clone objects before storing in storage object

    Hi,

    First let me thank you for the wonderful little tool you've created, very useful!

    I have run into a minor issue, which can be easily fixed (I'm no git user, so I didn't create a pull req for this).

    in set:

        set: function(key, value){
            _checkKey(key);
            if(_XMLService.isXML(value)){
                value = {_is_xml:true,xml:_XMLService.encode(value)};
            }
            _storage[key] = value;
            _save();
            return value;
        }
    

    If the value is an object, and it is later changed, the _storage cache will reflect those changes (while the localStorage won't). This is an issue, since the stored object may (and in my application does) acquire non-json-serializable properties (such as jQuery wrapped elements). when ever some other key is changed and the entire _storage object needs to be serialized, things break.

    my fix was quite simple, perhaps there's a better way to go about this-

    set: function(key, value){
            var clone;
            _checkKey(key);
            if(typeof(value) === 'object'){
                clone = $.extend(true, {}, value);
            }else{
                clone=value;
            }
            if(_XMLService.isXML(clone)){
                clone= {_is_xml:true,xml:_XMLService.encode(clone)};
            }
            _storage[key] = clone;
            _save();
            return clone;
    }
    

    Please note that this uses jQuery's extend function explicitly, I have no idea whether this could roll with other libraries. This works fine for me, so I hope it might help others as well.

    Thanks again, o

    opened by odedbd 4
  • Risky cache behaviour.

    Risky cache behaviour.

    Internal variable _storage is used for caching purposes. Suppose this example:

    var b = {
        abc: function(abc) {
            return abc + '!';
        }
    };
    
    $.jStorage.set('b', b);
    
    var b2 = $.jStorage.get('b');
    log(b2.abc(123)); //shows '123! ', but should be 'error - no method abc'.
    

    It gives the user the false understanding that he can store functions in storage. But we understand, that in browser storage his object has no 'abc' method.

    I think it is better to make cache real cache :)

    opened by MatveiFisenko 3
  • Error in IE6 and IE7 $.jStorage is null or not an object

    Error in IE6 and IE7 $.jStorage is null or not an object

    I just started using this for a site and it works great in IE8 and all other browsers I've tested on on all platforms. However, when I try it on my Windows XP boxes, one with IE6 and one with 7, I get the "null or not an object" error on page load. You can view my simplified test here: http://www.richpaul.com/dev/jstorage_test/

    Any insight would be appreciated.

    opened by richgithub 3
  • JStorage Max Allowed Size in browsers

    JStorage Max Allowed Size in browsers

    What is the max allowed size of JStorgae in different browsers(including mobile browsers)? I want to know this since I want to calculate the minimum of all the max allowed sizes and based on that I want to store some number of objects so that it can be used without any issue across most(almost any) browser(be it desktop or laptop or tablet or mobile based).

    Regards, Sandip

    opened by sandipray63in 2
  • Handle race conditions correctly

    Handle race conditions correctly

    Not even sure if the problem is in race conditions, since it involves just a single tab open. I used following code:

    <!doctype html>
    <script src="//cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>
    <script src="jstorage.js"></script>
    <script>
      var me = "Client"+Math.random();
      var received = 0;
      $.jStorage.subscribe("aaa",function(chanel,data){
        received++;
        console.log("received message no. " + data[0] + " from client " + data[1] + " so far received "+ received + " messages");
      });
      for(var i=0;i<1000;++i){
        $.jStorage.publish("aaa",[i,me]);
      }
    </script>
    

    I'd expect it to report 1000 received messages, but actually only around ~800 pass trough in "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" It looks like the missing messages are the initial ones.

    opened by qbolec 2
  • Uncaught TypeError

    Uncaught TypeError

    Hey Everyone,

    Everything was working great till recently and suddenly now I get the following errors throughout my website where jstorage is used Uncaught TypeError : Cannot read property 'get' of undefined

    This is my code for one part of my website

    if($.jStorage.get('my_guest')) {
          location = href;
        } else {
          LoginBox.checkActivate({img: img, title: title, cbRegisterURL: href,
                              onGuestClick: function(){location = href}});
        }
      } else {
        location = href;
      }
    

    Any help will be greatly appreciated. Thanks for your time

    opened by manatarms 2
  • Remove XML Support?

    Remove XML Support?

    I was wondering why XML Support is provided in the library...

    You are not providing JSON.stringify, JSON.parse etc inside the library, right? You expect users to make sure that JSON support is present.

    Not sure what percentage of users require XML support. I would dare to assume that the percentage is on the low side. Do you have any data on this?

    IMHO, XML support should be removed from the library. Users who want to work with XML should be expected to provide endode/decode methods. (Also, if somebody is already working with XML, it can be safely assumed that they already have some methods defined to help with this.)

    Even if the bytes saved are not huge, there is no need to support this out-of-the box IMHO. Should be at least moved out to a plugin.

    Thoughts?

    opened by niyazpk 2
  • Npm package update

    Npm package update

    Hi! Npm contains 0.4.8 version with ambiguous UNLICENSED license in package.json. Do you have an ability to upload latest version there? I am happy to asssit if you can share the ownership in npm.

    opened by udalmik 7
  • What is the scope of the data?

    What is the scope of the data?

    Forgive me if I have overlooked this somewhere, but what is the scope of the stored data? Can I set data in one page (example.com/foo) and retrieve it in another page on the same domain (example.com/bar)?

    To be clear, I definitely don't want this - I need to know if this is something I deliberately need to avoid by namespacing my keys in some way. I want to store separate values for the key baz on the two pages example.com/foo and example.com/bar.

    opened by cmeeren 5
  • JStorage does not give an indication it has run out of storage.

    JStorage does not give an indication it has run out of storage.

    https://github.com/andris9/jStorage/blob/5f4075a7e1736d5c7d65375288154a73ac895818/jstorage.js#L459-L470

    Looking at this code, if JStorage runs out of room, it will assume IE7 and kill the exception. This should be changed to at least display a warning in the console that JStorage was unable to save because local storage is full. This would save a lot of time.

    opened by rlloyd2001 0
Owner
Andris Reinman
Andris Reinman
Store your data in the world's fastest and most secure storage, powered by the blockchain technology⚡️

Store your data in the world's fastest and most secure storage, powered by the blockchain technology.

BlockDB 3 Mar 5, 2022
local storage wrapper for both react-native and browser. Support size controlling, auto expiring, remote data auto syncing and getting batch data in one query.

react-native-storage This is a local storage wrapper for both react native apps (using AsyncStorage) and web apps (using localStorage). ES6 syntax, pr

Sunny Luo 2.9k Dec 16, 2022
Browser storage interface for IndexedDB, WebSQL, LocalStorage, and in memory data with Schema and data validator.

Client Web Storage Browser storage interface for IndexedDB, WebSQL, LocalStorage, and in memory data with basic Schema and data validation. Installati

Before Semicolon 19 Sep 30, 2022
JavaScript Client-Side Cookie Manipulation Library

Cookies.js Cookies.js is a small client-side javascript library that makes managing cookies easy. Features Browser Compatibility Getting the Library U

Scott Hamper 1.8k Oct 7, 2022
:sunglasses: Everything you need to know about Client-side Storage.

awesome-web-storage Everything you need to know about Client-side Storage. Table of Contents Introduction Browser Support Cookies Pros Cons API Useful

Varun Malhotra 420 Dec 12, 2022
A lightweight clientside JSON document store,

.____ .__ .__ | | _____ __ _ ______ ____ | |__ _____ |__|_______ | | \__ \

Brian LeRoux 2.1k Nov 24, 2022
:lock: Secure localStorage data with high level of encryption and data compression

secure-ls Secure localStorage data with high level of encryption and data compression. LIVE DEMO Features Secure data with various types of encryption

Varun Malhotra 602 Nov 30, 2022
A simple, lightweight JavaScript API for handling browser cookies

JavaScript Cookie A simple, lightweight JavaScript API for handling cookies Works in all browsers Accepts any character Heavily tested No dependency S

null 20.2k Jan 3, 2023
Cross-browser storage for all use cases, used across the web.

Store.js Cross-browser storage for all use cases, used across the web. Store.js has been around since 2010 (first commit, v1 release). It is used in p

Marcus Westin 13.9k Dec 29, 2022
Expirable data storage based on localStorage and sessionStorage.

Expirable storage About The Project Expirable data storage based on localStorage and sessionStorage. Getting Started To get a local copy up and runnin

Wayfair Tech – Incubator 5 Oct 31, 2022
💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.

localForage localForage is a fast and simple storage library for JavaScript. localForage improves the offline experience of your web app by using asyn

localForage 21.5k Jan 4, 2023
💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.

localForage localForage is a fast and simple storage library for JavaScript. localForage improves the offline experience of your web app by using asyn

localForage 21.5k Jan 1, 2023
⁂ The simple file storage service for IPFS & Filecoin

⁂ web3.storage The simple file storage service for IPFS & Filecoin. Getting started This project uses node v16 and npm v7. It's a monorepo that use np

Web3 Storage 423 Dec 25, 2022
Simple window.localStorage, with type safety

mini-local-storage simple window.localStorage, with type safety example // localStorage.ts import { createLocalStorage } from "mini-local-storage";

Kipras Melnikovas 4 Jan 8, 2023
Tool to sign data with a Cardano-Secret-Key // verify data with a Cardano-Public-Key // generate CIP-8 & CIP-36 data

Tool to sign data with a Cardano-Secret-Key // verify data with a Cardano-Public-Key // generate CIP-8 & CIP-36 data

Martin Lang 11 Dec 21, 2022
Bookmate - Watch changes in Chrome bookmarks, and use bookmarks as an append-only key-value store via an fs-like API.

?? Bookmate An append-only key-value store built on Chrome bookmarks, plus an asychronous stream of Bookmark changes. For NodeJS Actual production exa

Cris 6 Nov 8, 2022
🪦 Redis Key Value store backed by IPFS

?? RipDB ?? A snappy, decentralized JSON store perfect for fast moving web3 builders. Redis + IPFS = RIP = ?? Install With a Package Manager (browser

Zac Denham 42 Dec 13, 2022
Persistent key/value data storage for your Browser and/or PWA, promisified, including file support and service worker support, all with IndexedDB. Perfectly suitable for your next (PWA) app.

BrowstorJS ?? ?? ?? Persistent key/value data storage for your Browser and/or PWA, promisified, including file support and service worker support, all

Nullix 8 Aug 5, 2022
Realm is a mobile database: an alternative to SQLite & key-value stores

Realm is a mobile database that runs directly inside phones, tablets or wearables. This project hosts the JavaScript versions of Realm. Currently we s

Realm 5.1k Jan 3, 2023
Fast and advanced, document based and key-value based NoSQL database that able to work as it is installed.

About Fast and advanced, document based and key-value based NoSQL database that able to work as it is installed. Features NoSQL database Can be run as

null 6 Dec 7, 2022