data-transport

A generic and responsible communication transporter

Usage no npm install needed!

<script type="module">
  import dataTransport from 'https://cdn.skypack.dev/data-transport';
</script>

README

data-transport

Node CI npm version

A generic and responsible communication transporter

Support Transport

  • iframe
  • Broadcast
  • Web Worker
  • Service Worker
  • Shared Worker
  • Browser Extension
  • WebRTC
  • Electron

Usage

  • Installation
yarn add data-transport
  • Define type
interface Internal {
  hello({ num: number }): Promise<{ text: string }>;
}
  • Create transports
const internal: Transport<Internal> = createTransport('IFrameInternal');
const external: Transport<any, Internal> = createTransport('IFrameMain');

external.listen('hello', async (options) => ({ text: `hello ${options.num}` }));

expect(await internal.emit('hello', { num: 42 }).toEqual({ text: 'hello 42' });

Another implementation based on inherited classes.

interface Internal {
  hello({ num: number }): Promise<{ text: string }>;
}

class InternalTransport extends IFrameTransport.IFrame<Internal> implement Internal {
  async hello(options: { num: number }) {
    const response = await this.emit('hello', options);
    return response;
  }
}

class ExternalTransport extends IFrameTransport.Main implements Internal {
  @listen
  async hello(options: { num: number }) {
    return {
      text: `hello ${options.num}`,
    };
  }
}

const internal = new InternalTransport();
const external = new ExternalTransport();

expect(await internal.hello({ num: 42 })).toEqual({ text: 'hello 42' });

Examples

Online with Broadcast