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.
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);
See examples/send-work-to-webview
Each side works as client and server the same time.