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
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
; // initianlizeconst bridge = protocol: 'custom_protocol' prefix: 'custom_prefix_'; windowbridge = 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. */ windowbridge;
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 */ windowbridge;
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. */windowbridge;
Get web passed params:
/** * Use bridge instance method getParam with prev handler */const params = windowbridge;// do something with params...// send to webwindowbridge;
4. Web event listener
Sometimes web need to listen event from SDK or native.
/** * Web add custom event */windowbridge; /** * SDK fire event at property time */windowbridge;
API
Bridge instance
method | params type | description |
---|---|---|
Bridge | options<BridgeOptions> | constructor |
getScheme | name<string> | get full scheme url |
getParam | handler<string> | get params registered |
nativeCall | scheme<string> params<?any> callback<?(d: any) => void> |
send message from web to sdk |
postMessage | e<string> | send message from sdk to web |
addEvent | name<string> callback<(e: CustomEvent) => void> |
web add event listener |
removeEvent | handler<string|number> | web remove event listener |
fireEvent | eventName<string> data<any> |
fire web event |
BridgeOptions
option | type | description |
---|---|---|
protocol | ?string | custom protocol |
prefix | ?string | url prefix |