const [isLoadEnd, setIsLoadEnd] = useState('hidden')
const WebViewRef = useRef<any>(null)
// rn接受到h5的postMessage发送的消息
const onMessage = (e: any) => {
console.log('args', e)
let actionData = e.nativeEvent.data
}
// rn 给h5发送消息
const onUploadChange = async (files: any[]) => {
console.log('onUploadChange', files)
const fileList: any[] = []
const initParams = JSON.stringify({
cmd: 'approval_rn_onUploadinit',
res: {
files: files
}
})
const initParamsJs = `window.receiveMessage('${initParams}');true;`
console.log(initParamsJs)
WebViewRef.current.injectJavaScript(initParamsJs)
}
// 由于react-native-webView 的onMessage不识别window.postMessage, 需要改成window.ReactNativeWebView.postMessage, 同时injectedJavascript只支持一行压缩代码,不支持多行,请勿换行和格式化;
const injectedJavascript = `if(window.ReactNativeWebView&&window.ReactNativeWebView.postMessage){;window.postMessage=function(data){var str=typeof data==='object'?JSON.stringify(data):data;window.ReactNativeWebView.postMessage(str)};window.parent.postMessage=window.postMessage};window.parent.postMessage({cmd:'rn-init',res:{'label':'这个只是测试rn能不能走通'}},'*');`
<RCWebView
ref={WebViewRef}
style={{
visibility:isLoadEnd
}}
source={{
uri: encodeURI(url)
}}
injectedJavaScript={injectedJavascript}
mixedContentMode={'compatibility'}
scalesPageToFit={false}
javaScriptEnabled={true}
startInLoadingState={true}
renderLoading={() => {
return isLoadEnd === 'hidden' ? (
<View style={{ flex: 1, backgroundColor: '#fff' }}>
<ActivityIndicator size="large" />
</View>
) : (
<></>
)
}}
onLoadEnd={() => {
console.log('loadend')
Toast.removeAll()
setIsLoadEnd('visible')
}}
onError={() => {
console.log('error')
}}
onMessage={onMessage}
/>
h5给rn发送消息
window.parent.postMessage({cmd:'rn-init',res:{'label':'这个只是测试rn能不能走通'}},'*');
网友评论