React-Native WebView 数据交互

本文档记录了 React Native 与 react-native-webview 互传数据时的细节

参考文档:https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#communicating-between-js-and-native

数据交互分别为两类,使用场景会一一介绍:

  • React Native 发送消息到 Web
    • injectedJavaScrit prop
    • injectedJavaScriptBeforeContentLoaded prop
    • injectJavaScript method
    • WebView postMessage method
  • Web 发送消息到 React Native
    • HTML5 postMessage method and onMessage prop

message 类型均为 string

一、React Native 发送消息到 Web#

1.injectedJavaScript#

参考 https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#the-injectedjavascript-prop

2.injectedJavaScriptBeforeContentLoaded#

参考 https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#the-injectedjavascriptbeforecontentloaded-prop

3.injectJavaScript#

参考 https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#the-injectjavascript-method

4.WebView postMessage#

HTML5 要监听 RN 传递过来的 message 消息,注意 Android 和 iOS 不一样:

<html>
<head></head>
<body>
<script>
// Android 监听
document.addEventListener("message", (event) => {
window.alert('document: ' + event.data);
}, false);
// iOS 监听
window.addEventListener("message", (event) => {
window.alert('window: ' + event.data);
}, false);
</script>
</body>
</html>

RN 通过 ref 调用 postMessage 发送 message:

const NewWebView = props => {
const webref = React.useRef();
const { uri } = props;
const onPress = () => {
webref.current.postMessage('React Native -> Web');
}
return (
<View style={{ flex: 1 }}>
<WebView
ref={webref}
source={{ uri }}
/>
<Button
onPress={onPress}
title="postMessage to Web"
/>
</View>
);
}

二、Web 发送消息到 React Native#

1.HTML5 postMessage method and onMessage prop#

HTML5 要用 window.ReactNativeWebView.postMessage 发送消息:

<html>
<head></head>
<body>
<div id="btn">postMessage to Native</div>
<script>
const btn = document.getElementById("btn");
btn.addEventListener('click',() => {
window.ReactNativeWebView.postMessage("Web -> React Native")
}, false);
</script>
</body>
</html>

RN 利用 onMessage 方法监听消息:

const NewWebView = props => {
const { uri } = props;
const onWebMessageListener = e => {
// data 为字符串
const { data } = e.nativeEvent;
console.log(data);
}
return (
<WebView
style={{ flex: 1 }}
source={{ uri }}
onMessage={onWebMessageListener}
/>
)
}