1.0.3 • Published 3 years ago

web-sdk-bridge v1.0.3

Weekly downloads
1
License
ISC
Repository
github
Last release
3 years ago

web-sdk-bridge

Introduction

A bridge for web and sdk two way messages. For hybrid app send messages.

Inspired by this article Hybrid App技术解析 -- 实战篇

Architecture

architecture

Features

  • Build with ESM
  • No external dependencies
  • Easy to setup and use
  • Based on customEvents and custom schema

Install

> npm i web-sdk-bridge --save

Setup

1. Initialize

import Bridge from 'web-sdk-bridge';

// initianlize
const bridge = new Bridge({
  protocol: 'custom_protocol',
  prefix: 'custom_prefix_',
});

window.bridge = bridge;

2. Send message from web to SDK

Basic usage:

/**
 * This will actually send a get request with
 * this url: custom_protocol://custom_prefix_select_photo/?handler=0.
 */ 
window.bridge.nativeCall(
  'select_photo',
);

Pass params and callback:

/**
 * This will actually send a get request with
 * this url: custom_protocol://custom_prefix_select_photo/?handler=0.
 * SDK need to parse the url to get the params
 */ 
window.bridge.nativeCall(
  'select_photo',
  {
    count: 1,
  },
  (data) => {
    // dosomething with the data
  },
);

3. Send message from SDK to web

Basic usage:

/**
 * Alternatively, javascript can assign the bridge object to window,
 * so that SDK (like ios and android) can access
 * the Bridge instance method.
 */
window.bridge.postMessage(
  {
    handler: 0, // required handler from nativeCall url query
    data: {
      result: 'success',
      images: [],
    },
  }
);

Get web passed params:

/**
 * Use bridge instance method getParam with prev handler
 */
const params = window.bridge.getParam(handler);
// do something with params...
// send to web
window.bridge.postMessage(
  {
    handler: 0, // required handler from nativeCall url query
    data: {
      result: 'success',
      images: [],
    },
  }
);

4. Web event listener

Sometimes web need to listen event from SDK or native.

/**
 * Web add custom event
 */
window.bridge.addEvent('my_custom_event', (ev) => {
  const data = ev.data;
  // dosomething with the data...
});

/**
 * SDK fire event at property time
 */
window.bridge.fireEvent('my_custom_event', {
  a: 1,
  b: 2,
  ...
});

API

Bridge instance

methodparams typedescription
Bridgeoptions\constructor
getSchemename\get full scheme url
getParamhandler\get params registered
nativeCallscheme\params\<?any>callback\<?(d: any) => void>send message from web to sdk
postMessagee\send message from sdk to web
addEventname\callback\<(e: CustomEvent) => void>web add event listener
removeEventhandler\<string|number>web remove event listener
fireEventeventName\data\fire web event

BridgeOptions

optiontypedescription
protocol?stringcustom protocol
prefix?stringurl prefix
1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago