react-native与webview的通信
2023-04-20 本文已影响0人
sunny635533
实现RN和webview互相发送文本通信
html内容=>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>启动测试</title>
</head>
<body>
<p style="text-align: center">
<button id="button">发送数据到react native</button>
<p style="text-align: center">收到react native发送的数据: <span id="data"></span></p>
</p>
<script>
var data = 0;
//webview发送内容到RN
function sendData(data) {
window.ReactNativeWebView.postMessage(data);
}
window.onload = function () {
//ios的监听RN传递过来的事件
window.addEventListener('message', function (e) {
alert("==== e111 ====" + e.data)
document.getElementById('data').textContent = e.data;
});
//android的监听RN传递过来的事件
document.addEventListener('message', function (e) {
alert("==== e2222 ====" + e.data)
document.getElementById('data').textContent = e.data;
});
document.getElementById('button').onclick = function () {
data += 100;
sendData(data);
}
}
</script>
</body>
</html>
react-native的页面代码=>
import React, { Component } from "react";
import { Image, StyleSheet, Animated, Text, TextInput, TouchableOpacity, View, Platform } from "react-native";
import WebView from "react-native-webview";
export default class TestWebViewPage extends Component {
webViewRef = React.createRef();
constructor(props) {
super(props);
this.state = {
webViewData: ""
}
this.data = 0;
}
sendMessage() {
this.data += 1;
this.webViewRef.current?.postMessage(JSON.stringify(this.data));
}
handleMessage(e) {
console.log("==== handleMessage ==", e.nativeEvent.data)
this.setState({ webViewData: e.nativeEvent.data });
}
render() {
const injectedJavascript = "javascript:function deliverCode(data) { window.ReactNativeWebView.postMessage(data) };"
const url = Platform.select({
ios: require('../../../test.html'),
android: { uri: "file:///android_asset/test.html" }
})
return <View style={{ flex: 1 }}>
<NavBar>webview通信</NavBar>
<View style={{ margin: 20 }}>
<UIButtonWithSingleText
textStyle={{ color: 'green' }}
text={"发送数据到webview"}
onPress={() => {
this.sendMessage()
}} />
<Text style={{ color: '#f00' }}>{this.state.webViewData}</Text>
</View>
<WebView
ref={this.webViewRef}
source={url}
style={{ flex: 1 }}
onMessage={(e) => {
this.handleMessage(e)
}}
injectedJavaScript={injectedJavascript}
startInLoadingState={true}
javaScriptEnabled={true}
domStorageEnabled={true}
scrollEnabled={false}
allowFileAccess={true}
androidHardwareAccelerationDisabled={true}
automaticallyAdjustContentInsets={true}
scalesPageToFit={Platform.OS !== "ios"}
originWhitelist={['*']}
/>
</View>
}
}
injectedJavascript 注入js代码测试,iOS可以用,但是android不行。