react-native-webview-invoke
Invoke functions between React Native and WebView directly
react-native-webview-bridge
Support
Just like:
// Side Aconst answer = await// Side B{ return 'I don\'t know' }
Before using like that, you should firstly define the function you want to expose.
// Side Aconst ask = invoke// Side Binvoke
Installation
$ npm install react-native-webview-invoke --save
Requires:
- React Native >= 0.37
Basic Usage
There are two sides: native and web.
React Native Side
Import
Create invoke
Componentwebview: WebViewinvoke ={// Note: add 'useWebKit' property for rn > 0.59return <Webview useWebKitref= thiswebview = webviewonMessage=thisinvokelistenersource=/>}
Now, we can start to expose functions for Web, and get the function from Web. (See Start to use)
Web Side
Import
Or use <script>
in .html
Start to use
For better illumination, we define two sides named A
and B
. each of them can be React Native or Web, and if A
is React Native, then B
is Web.
Assume that there are some functions in A side.
{return 'A'}{return 'Hi, ' + prefix + someone + '!'}
Expose them for B side.
invoke
OK, Go to the B side:
Firstly, bind some functions which exposed from A
.
const whatIsTheNameOfA = invokeconst tellAYouArea = invoke
Now, we can use them.
await// 'A'await// 'Hi, Mr.B'
In addition, you can use them without definition too.
await invokefn// 'A'await invokefn// 'Hi, Mr.B'
API
createInvoke(getWebViewInstance)
(RN only) create
invoke
with theWebview
instance.
Args:
- getWebViewInstance [
() => React.WebView
] getter forWebview
instance
Return:
- invoke [
invoke
] invoke object
invoke.define(name, fn)
expose function to another side.
Args:
- name [
string
] function name - fn [
Function
]
invoke.bind(name)
get function from another side
Args:
- name [
string
] function name
Return:
[(...args: any[]) => Promise<any>
] function
invoke.fn
All functions that defined at the other side
Usage
// A sideinvoke// B sideinvokefn
invoke.listener
(RN only) the handler for the
onMessage
property ofWebView
element.
Usage:
<WebView onMessage=invokelistener />