react-native-webview-messager
v0.0.2
Published
Easer async/await based messager for react native webview
Downloads
4
Maintainers
Readme
react-native-webview-messager
react-native-webview-messager provides a useful API using async / await for easier communicating with react native webview.
Jusk like:
// one side
const answer = await messager.send('ask', question)
// another side
messager.on('ask', question => 'I don\'t know')
Installation
$ npm install react-native-webview-messager --save
Require
- React Native >= 0.37
Basic Usage
There are two side of the lib
React Native Side Import
Import the createMessager
function
import createMessager from 'react-native-webview-messager/native'
Init the messager
class SomePage extends React.Component {
webview: WebView
messager = createMessager(() => this.webview)
render() {
return <Webview
ref={webview => this.webview = webview}
onMessage={this.messager.listener}
source={require('./index.html')}
/>
}
}
Web Side Import
Import the messager
import messager from 'react-native-webview-messager/browser'
Or
<script src="./node_modules/react-native-webview-messager/browser.js"></script>
<script>
var messager = window.WebViewMessager
</script>
Start
One side
// registry a listener
const me = { name: 'NO.19', nickname: 'Jack' }
const thinking = () => new Promise(resolve => setTimeout(resolve, 2000))
messager.on('what is your', async (q) => {
await thinking()
return me[q] || 'I don\'t know'
})
Another side
const name = await messager.send('what is your', 'name')
// 'NO.19'
API
on(command, callback)
bind a command handler
Args:
- command [
string
] - callback [
(payload: any) => any | Promise<any>
]
off(command)
unbind a command
Args:
- command [
string
]
send(command, payload)
send a message to another side
Args:
- command [
string
] - payload [
any
]
Return
- [
Promise<any>
]
listener(evt)
onMessage handler for WebView component (only at the native side)
Args:
- evt [
nativeEvent
]
Example:
<WebView onMessage={messager.listener} />
Custom Usage
react-native-webview-messager
also provide a factory function for creating custom messager in other webview bridge lib like react-native-webview-bridge
import messagerFactory from 'react-native-webview-messager/factory'
Use react-native-webview-bridge#v2
as an example.
React Native Side:
import { WebViewBridge } from 'react-native-webview-bridge'
import messagerFactory from 'react-native-webview-messager/factory'
class Test extends React.Component {
webview: WebViewBridge
messager = messagerFactory((v) => this.webview.sendToBridge(v))
render() {
return (
<WebViewBridge
ref={w => this.webview = w}
onMessage={this.messager.listener}
/>
)
}
}
Web Side:
import messagerFactory from 'react-native-webview-messager/factory'
const messager = messagerFactory(v => window.WebViewBridge(v))
window.WebViewBridge.addMessageListener(messager.listener)
Factory API
messagerFactory(sender)
Create a messager
Args
- sender [
(data: any) => void
] define how to send a message object