localforage vs broadcast-channel vs comlink
Web Communication and Storage Libraries Comparison
1 Year
localforagebroadcast-channelcomlinkSimilar Packages:
What's Web Communication and Storage Libraries?

This collection of libraries facilitates communication between different parts of a web application and provides efficient storage solutions. Each library serves a unique purpose, whether it's enabling cross-tab communication, simplifying remote procedure calls, or enhancing local storage capabilities. These libraries help developers create responsive, efficient, and user-friendly applications by managing data and interactions seamlessly across various contexts.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
localforage4,365,43425,209-2474 years agoApache-2.0
broadcast-channel2,032,3141,887535 kB11a year agoMIT
comlink624,43211,671252 kB1114 months agoApache-2.0
Feature Comparison: localforage vs broadcast-channel vs comlink

Communication Method

  • localforage:

    LocalForage does not focus on communication but rather on data storage. It provides a unified API for storing data in various formats and backends, allowing for seamless data retrieval and storage without needing to manage different storage mechanisms directly.

  • broadcast-channel:

    Broadcast Channel uses a simple pub/sub model to facilitate communication between different browsing contexts (tabs, windows, iframes) of the same origin. It allows for broadcasting messages to all listening contexts, making it easy to synchronize state across them.

  • comlink:

    Comlink leverages the concept of proxies to simplify communication between the main thread and web workers. It allows you to call functions in a worker as if they were local, abstracting away the complexity of postMessage and event listeners, thus streamlining the development process.

Use Cases

  • localforage:

    Perfect for applications that need to store large amounts of data offline or require fast access to data. It is commonly used in progressive web apps (PWAs) and applications that need to function without a consistent internet connection.

  • broadcast-channel:

    Ideal for applications that require real-time updates across multiple tabs, such as collaborative editing tools, chat applications, or any scenario where user actions in one tab need to be reflected in others immediately.

  • comlink:

    Best suited for applications that perform heavy computations or need to offload tasks to web workers. It is particularly useful in scenarios where you want to maintain responsiveness in the UI while processing data in the background.

Ease of Use

  • localforage:

    LocalForage provides a simple and familiar API similar to localStorage, but with the added benefits of asynchronous operations and support for various storage backends. This makes it easy for developers to transition from localStorage to a more robust solution.

  • broadcast-channel:

    Broadcast Channel is straightforward to implement, requiring minimal setup to start sending and receiving messages. Its API is simple and intuitive, making it accessible for developers of all skill levels.

  • comlink:

    Comlink simplifies the complexity of using web workers, allowing developers to focus on writing business logic without worrying about the underlying message-passing mechanics. Its API is designed to be easy to understand and use, reducing the learning curve significantly.

Performance

  • localforage:

    LocalForage is built for speed, utilizing asynchronous storage mechanisms to ensure that data operations do not block the main thread. It is optimized for performance, especially when dealing with larger datasets, making it a reliable choice for offline storage.

  • broadcast-channel:

    Broadcast Channel is optimized for performance, allowing for quick message passing between contexts without the overhead of server communication. However, performance may vary depending on the number of listeners and the frequency of messages being sent.

  • comlink:

    Comlink is designed to minimize the performance overhead associated with message passing. By using proxies, it reduces the boilerplate code and improves the efficiency of communication between the main thread and workers, making it suitable for performance-critical applications.

Browser Compatibility

  • localforage:

    LocalForage provides a fallback mechanism, ensuring that if a preferred storage method is not available, it will automatically use the next available option. This makes it highly compatible across different browsers and environments.

  • broadcast-channel:

    Broadcast Channel is supported in modern browsers, but developers should check compatibility for older versions or specific environments, as it may not be available in all contexts.

  • comlink:

    Comlink is compatible with modern browsers that support web workers. Developers should ensure that their target browsers support the necessary features for optimal performance.

How to Choose: localforage vs broadcast-channel vs comlink
  • localforage:

    Opt for LocalForage if you require a robust and flexible solution for offline storage that supports various storage backends (IndexedDB, WebSQL, and localStorage). It provides a simple API for storing and retrieving data asynchronously, making it suitable for applications that need to work offline or manage large amounts of data efficiently.

  • broadcast-channel:

    Choose Broadcast Channel if you need to enable real-time communication between different tabs or windows of the same origin. It is ideal for scenarios where you want to synchronize state or notify other parts of your application about changes without relying on server communication.

  • comlink:

    Select Comlink if you want to simplify the process of remote procedure calls (RPC) between the main thread and web workers. It abstracts the complexity of message passing and allows you to call functions directly as if they were local, making it perfect for offloading heavy computations to web workers while keeping the code clean and manageable.

README for localforage

localForage

Build Status NPM version Dependency Status npm jsDelivr Hits minzipped size

localForage is a fast and simple storage library for JavaScript. localForage improves the offline experience of your web app by using asynchronous storage (IndexedDB or WebSQL) with a simple, localStorage-like API.

localForage uses localStorage in browsers with no IndexedDB or WebSQL support. See the wiki for detailed compatibility info.

To use localForage, just drop a single JavaScript file into your page:

<script src="localforage/dist/localforage.js"></script>
<script>localforage.getItem('something', myCallback);</script>

Try the live example.

Download the latest localForage from GitHub, or install with npm:

npm install localforage

Support

Lost? Need help? Try the localForage API documentation. localForage API文档也有中文版。

If you're having trouble using the library, running the tests, or want to contribute to localForage, please look through the existing issues for your problem first before creating a new one. If you still need help, feel free to file an issue.

How to use localForage

Callbacks vs Promises

Because localForage uses async storage, it has an async API. It's otherwise exactly the same as the localStorage API.

localForage has a dual API that allows you to either use Node-style callbacks or Promises. If you are unsure which one is right for you, it's recommended to use Promises.

Here's an example of the Node-style callback form:

localforage.setItem('key', 'value', function (err) {
  // if err is non-null, we got an error
  localforage.getItem('key', function (err, value) {
    // if err is non-null, we got an error. otherwise, value is the value
  });
});

And the Promise form:

localforage.setItem('key', 'value').then(function () {
  return localforage.getItem('key');
}).then(function (value) {
  // we got our value
}).catch(function (err) {
  // we got an error
});

Or, use async/await:

try {
    const value = await localforage.getItem('somekey');
    // This code runs once the value has been loaded
    // from the offline store.
    console.log(value);
} catch (err) {
    // This code runs if there were any errors.
    console.log(err);
}

For more examples, please visit the API docs.

Storing Blobs, TypedArrays, and other JS objects

You can store any type in localForage; you aren't limited to strings like in localStorage. Even if localStorage is your storage backend, localForage automatically does JSON.parse() and JSON.stringify() when getting/setting values.

localForage supports storing all native JS objects that can be serialized to JSON, as well as ArrayBuffers, Blobs, and TypedArrays. Check the API docs for a full list of types supported by localForage.

All types are supported in every storage backend, though storage limits in localStorage make storing many large Blobs impossible.

Configuration

You can set database information with the config() method. Available options are driver, name, storeName, version, size, and description.

Example:

localforage.config({
    driver      : localforage.WEBSQL, // Force WebSQL; same as using setDriver()
    name        : 'myApp',
    version     : 1.0,
    size        : 4980736, // Size of database, in bytes. WebSQL-only for now.
    storeName   : 'keyvaluepairs', // Should be alphanumeric, with underscores.
    description : 'some description'
});

Note: you must call config() before you interact with your data. This means calling config() before using getItem(), setItem(), removeItem(), clear(), key(), keys() or length().

Multiple instances

You can create multiple instances of localForage that point to different stores using createInstance. All the configuration options used by config are supported.

var store = localforage.createInstance({
  name: "nameHere"
});

var otherStore = localforage.createInstance({
  name: "otherName"
});

// Setting the key on one of these doesn't affect the other.
store.setItem("key", "value");
otherStore.setItem("key", "value2");

RequireJS

You can use localForage with RequireJS:

define(['localforage'], function(localforage) {
    // As a callback:
    localforage.setItem('mykey', 'myvalue', console.log);

    // With a Promise:
    localforage.setItem('mykey', 'myvalue').then(console.log);
});

TypeScript

If you have the allowSyntheticDefaultImports compiler option set to true in your tsconfig.json (supported in TypeScript v1.8+), you should use:

import localForage from "localforage";

Otherwise you should use one of the following:

import * as localForage from "localforage";
// or, in case that the typescript version that you are using
// doesn't support ES6 style imports for UMD modules like localForage
import localForage = require("localforage");

Framework Support

If you use a framework listed, there's a localForage storage driver for the models in your framework so you can store data offline with localForage. We have drivers for the following frameworks:

If you have a driver you'd like listed, please open an issue to have it added to this list.

Custom Drivers

You can create your own driver if you want; see the defineDriver API docs.

There is a list of custom drivers on the wiki.

Working on localForage

You'll need node/npm and bower.

To work on localForage, you should start by forking it and installing its dependencies. Replace USERNAME with your GitHub username and run the following:

# Install bower globally if you don't have it:
npm install -g bower

# Replace USERNAME with your GitHub username:
git clone git@github.com:USERNAME/localForage.git
cd localForage
npm install
bower install

Omitting the bower dependencies will cause the tests to fail!

Running Tests

You need PhantomJS installed to run local tests. Run npm test (or, directly: grunt test). Your code must also pass the linter.

localForage is designed to run in the browser, so the tests explicitly require a browser environment. Local tests are run on a headless WebKit (using PhantomJS).

When you submit a pull request, tests will be run against all browsers that localForage supports on Travis CI using Sauce Labs.

Library Size

As of version 1.7.3 the payload added to your app is rather small. Served using gzip compression, localForage will add less than 10k to your total bundle size:

minified
`~29kB`
gzipped
`~8.8kB`
brotli'd
`~7.8kB`

License

This program is free software; it is distributed under an Apache License.


Copyright (c) 2013-2016 Mozilla (Contributors).