react-native-webview-comlink
’s goal is to integrate the Comlink with React Native WebView component, allow the js in web browser calls native API.
Comlink
: npm i --save react-native-webview-comlink comlinkjs
expo-cli
, it needs to be ejected by npm run eject
import { WebView } from 'react-native-webview';
import { withComlinkExpose } from 'react-native-webview-comlink';
// root api object for web side to call
const rootObj = {
someMethod() {
console.warn('someMethod called');
},
};
const WebViewComponent = withComlinkExpose(rootObj)(WebView);
// render with the <WebViewComponent />
import { createEndpoint } from 'react-native-webview-comlink';
import { proxy } from 'comlinkjs';
const proxyObj = proxy(createEndpoint());
// call native side method
proxyObj.someMethod();
There are example React Native project and Web project(React) in examples directory
withComlinkExpose(obj, options)(WebView)
Returns a higher-order React WebView component class that has obj
exposed via comlink
.
options
] (Object): if specified, customized the behavior of the higher-order WebView component.
forwardRef
] (Boolean): forward ref to the wrapped component, default is false
whitelistUrls
] (String or RegExp Array): white list urls where Comlink
enabled, default is null
isEnabled
] (Function): for control Comlink enable or disable status, it gets called in sending and receiving each message, returns true
to let the message pass, default is null
log
] (Boolean): print debug log to console, default is false
createEndpoint()
Returns an endpoint
for comlink
to use.
getEndpointStatus()
Returns current endpoint
status in ReadyStatusEnum
described below.
ReadyStatusEnum {
Pending = 0,
Ready = 1,
Failed = -1,
}
waitEndpointReady()
Returns a Promise
that resolves when endpoint
is ready or rejects on timeout.
comlink
depends on some ES6+ features such as Proxy, Generator Function, Symbol. babel-polyfill and proxy-polyfill may need to be included to get it work with legacy browsers.
Author: rocwind
Source Code: https://github.com/rocwind/react-native-webview-comlink
#react-native #react #mobile-apps