mole-rpc-transport-react-native
v1.0.1
Published
Easy way to communicate between react-native/webview using Mole-RPC (JSON RPC library)
Downloads
346
Maintainers
Readme
ReactNative/WebView Transport for Mole RPC (JSON RPC Library)
Setup communication between React Native and code inside WebView with just several lines of code.
Mole-RPC is a tiny transport agnostic JSON-RPC 2.0 client and server which can work both in NodeJs, Browser, Electron etc.
This is Event Emitter (window) based transport but there are many more transports.
Mole-RPC has zero dependencies and is a very small library.
Usage example (with simplified API)
react-native-index.js
import MoleClient from 'mole-rpc/MoleClient';
import Transport from 'mole-rpc-transport-react-native/Transport';
export default class ReactNativeApp extends React.PureComponent {
constructor(...params) {
super(...params);
this.webViewRef = React.createRef();
}
componentDidMount() {
this.initMoleRPC(this.webViewRef.current);
}
async initMoleRPC(webViewRef) {
const client = new MoleClient({
requestTimeout : 1000,
transport : new Transport({ windowListener: webViewRef })
});
}
render() {
return (
<WebView
ref = {this.webViewRef}
/>
);
}
}
webview-index.js
import MoleServer from 'mole-rpc/MoleServer';
import Transport from 'mole-rpc-transport-react-native/Transport.js';
import WindowListener from 'mole-rpc-transport-react-native/WindowListener.js';
const sum = (a, b) => a + b;
const multiply = (a, b) => a * b;
async function main() {
const server = new MoleServer({
transports: [
new Transport({
windowListener: new WindowListener()
})
]
});
server.expose({ sum, multiply });
await server.run();
}
main().catch(console.error);
More examples
Standard API for sending work to your web view from React Native.
See examples/send-work-to-webview
Bidirectional connection
Each side works as client and server the same time.