@conclurer/local-storage-fallback
    TypeScript icon, indicating that this package has built-in type declarations

    1.0.2 • Public • Published

    Local Storage Fallback

    Check and use appropriate storage adapter for browser (localStorage, sessionStorage, cookies, memory).

    Rewritten in Typescript from original local-storage-fallback by ripeworks.

    npm version

    Installation

    $ npm install @conclurer/local-storage-fallback
    

    Usage

    Basic Usage

    import {FallbackStorage} from '@conclurer/local-storage-fallback';
     
    // Auto detect supported storage adapter (default behavior)
    let storage = new FallbackStorage();
    storage.setItem('foo', 'bar');
    storage.getItem('foo'); // => 'bar'

    Use as Shim for localStorage

    To use local-storage-fallback as shim just import:

    import '@conclurer/local-storage-fallback/shim';

    Or add the following lines:

    import {FallbackStorage} from '@conclurer/local-storage-fallback';
     
    if (!('localStorage' in window)) {
        // tslint:disable-next-line
        (<any>window).localStorage = new FallbackStorage();
    }

    Specify Storage Adapter

    import {FallbackStorage, MemoryStorage} from '@conclurer/local-storage-fallback';
     
    let adapter = new MemoryStorage();
    let storage = new FallbackStorage(adapter);

    Custom Storage Adapters

    Custom storage adapters can be used by implementing the IStorageAdapter interface:

    import {FallbackStorage, IStorageAdapter} from '@conclurer/local-storage-fallback';
     
    class CustomAdapter implements IStorageAdapter {
      // Custom implementation
    }
     
    let storage = new FallbackStorage(new CustomAdapter());
     

    Purpose

    With browser settings like "Private Browsing" it has become a problem to rely on a working window.localStorage, even in newer browsers. Even though it may exist, it will throw exceptions when trying to use setItem or getItem. This module will run appropriate checks to see what browser storage mechanism might be available, and then expose it. It uses the same API as localStorage so it should work as a drop-in replacement in most cases.

    Gotchas

    • CookieStorage has storage limits. Be careful here.
    • MemoryStorage will not persist between page loads. This is more or less a stop-gap to prevent page crashes, but may be sufficient for websites that don't do full page loads.

    Keywords

    Install

    npm i @conclurer/local-storage-fallback

    DownloadsWeekly Downloads

    153

    Version

    1.0.2

    License

    MIT

    Last publish

    Collaborators

    • avatar
    • avatar