Bidirectional Channel for JavaScript

0.0.4 · active · verified Sun Apr 19

BIDC is a JavaScript library designed for establishing robust, asynchronous, bidirectional communication channels between different JavaScript execution contexts, such as web workers, iframes, and service workers. Unlike traditional `postMessage` APIs, BIDC abstracts away the complexities of message passing, providing full support for promises, async functions, and a wide range of complex data types (e.g., Date, RegExp, Map, Set, ArrayBuffer). It features an automatic handshake mechanism to establish and re-establish connections seamlessly, even if one side reloads, and buffers messages until the recipient is ready. Currently at version 0.0.4, the library is in an early development stage, focusing on foundational features for secure and efficient cross-context communication. Its primary differentiators are automatic connection management, comprehensive data type serialization, and first-class async/await support, streamlining RPC-style interactions. It ships with TypeScript types, enhancing developer experience and type safety.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic one-way data transfer and response handling between a parent window and an iframe using `createChannel`, showing both sending and receiving sides.

import { createChannel } from 'bidc';

// --- Parent window code ---
async function parentContext() {
  const iframe = document.createElement('iframe');
  document.body.appendChild(iframe);

  // Wait for iframe to load for contentWindow to be available
  await new Promise(resolve => iframe.onload = resolve);

  const { send } = createChannel(iframe.contentWindow);

  // Send a simple message to the iframe and await its response
  const result = await send({ value: 'Hello, iframe from parent!' });
  console.log('Parent received:', result);
  console.assert(result === 'HELLO, IFRAME FROM PARENT!');
}

// --- Inside the iframe (hypothetical, or simulated for demo) ---
// In a real scenario, this would be in the iframe's HTML or JS file.
function iframeContext() {
  // Omitting the target here will create a channel to the parent window by default
  const { receive } = createChannel(); // Equivalent to createChannel(window.parent)

  // Handle incoming messages from the parent and return a response
  receive((payload) => {
    console.log('Iframe received:', payload);
    if (typeof payload.value === 'string') {
      return payload.value.toUpperCase();
    }
    return 'Invalid payload';
  });
}

// For demonstration, call both, but in reality they run in separate contexts.
parentContext();
iframeContext(); // This would typically be loaded by the iframe itself.

view raw JSON →