UNPKG

lepont

Version:

A native <-> browser (webview) bridge library for react-native

90 lines 2.41 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const events_1 = require("events"); let cnt = 0; /** * Returns an unique id. */ function uniqId() { return cnt++; } class Bridge extends events_1.EventEmitter { constructor() { super(...arguments); this.resolverTable = {}; } recv(p) { const type = p.type; switch (p.type) { case 'result': this.onResult(p); break; case 'event': this.onEvent(p.message); break; default: throw new Error(`Unknown bridge payload type ${type}`); } } /** * Handles the message from the webview. */ onEvent({ type, payload }) { this.emit(type, payload); } /** * Handles the result from the webview's BridgeHandler. */ onResult(resPayload) { const { id, message, error } = resPayload; const resolver = this.resolverTable[id]; if (!resolver) { console.error(`Resolver for id=${id} not found.`); return; } delete this.resolverTable[id]; const [resolve, reject] = resolver; if (error) { reject(new Error(error.message)); } else { const { type, payload } = message; resolve(payload); } } /** * Sends a message to webview's bridge handler. */ async sendMessage(message) { const id = uniqId(); window.ReactNativeWebView.postMessage(JSON.stringify({ id, message })); return new Promise((resolve, reject) => { this.resolverTable[id] = [resolve, reject]; }); } } const bridge = new Bridge(); function sendMessage(m) { return bridge.sendMessage(m); } exports.sendMessage = sendMessage; function on(type, cb) { return bridge.on(type, cb); } exports.on = on; function off(type, cb) { return bridge.off(type, cb); } exports.off = off; Object.assign(window, { LePont: bridge }); function checkEnvironment(w = window) { if (typeof w.ReactNativeWebView === 'undefined') { throw new Error('ReactNativeWebView is undefined. Did you set onMessage of WebView?'); } } exports.checkEnvironment = checkEnvironment; setTimeout(checkEnvironment, 300); //# sourceMappingURL=browser.js.map