I have used the componentDidMount method which sending data properly to webview but i want to send data webview when I click on particular react native button.
In this webview is displaying the local html page and in this I’m sending the data to webview and on load event in html page alert the data which sent by react native in this componentdidmount method is succesfully sending data to webview html page but when I’m trying same code in method which saying that this.input
is undefined.
JavaScript
x
34
34
1
export default class HtmlRender extends Component {
2
3
//error:this.input is undefined
4
sendData() {
5
this.input.postMessage( data )
6
}
7
8
// This Is working
9
componentDidMount(){
10
this.input.postMessage( data)
11
}
12
13
14
render(){
15
return (
16
<View style={styles.fullContainer}>
17
<View style={styles.webviewBorder} >
18
19
<WebView
20
ref={(input) => this.input = input}
21
source={{uri:'file:///android_asset/Page.html'}}
22
/>
23
</View>
24
<View >
25
<Button onPress={this.sendData}>
26
<Text>
27
Data
28
</Text>
29
</Button>
30
</View>
31
</View >
32
33
)}
34
Advertisement
Answer
In short
Sending Data from Native(Webview) to Web App
JavaScript
1
8
1
// Native
2
this.webviewRef.postMessage('Wayne is coming!!!')
3
4
// Web
5
window.addEventListener("message", message => {
6
console.log(message.data) // Wayne is coming!!!
7
});
8
Sending data from Web App to Native(Webview)
JavaScript
1
16
16
1
// Web App
2
<button onClick={() => {
3
if(window.ReactNativeWebView) { // ensure window.ReactNativeWebView is there, otherwise, web app might crash if is not there
4
window.ReactNativeWebView.postMessage('Wayne is coming again')
5
}
6
}}>
7
</button>
8
9
// Native App
10
<WebView
11
onMessage={(event) => {
12
console.log(event.nativeEvent.data) // Client received data
13
}}
14
source={{ uri: 'https://your.domain.com' }}
15
/>
16
Full Example React Native Code
JavaScript
1
32
32
1
import React, { Component } from 'react';
2
import { WebView } from 'react-native-webview';
3
import { View, Button } from 'react-native';
4
5
class App extends Component {
6
constructor(props) {
7
super(props)
8
this.webviewRef = null;
9
}
10
render() {
11
return (
12
<>
13
<View style={{ flex: 1, alignContent: 'center', justifyContent: 'center' }}>
14
<Button
15
title="Press me"
16
onPress={() => {
17
this.webviewRef.postMessage('Wayne is coming!!!')
18
}}
19
/>
20
</View>
21
<WebView
22
onMessage={ (event) => {
23
console.log(event.nativeEvent.data) // Client received data
24
}}
25
source={{ uri: 'https://your.domain.com' }}
26
ref={ref => this.webviewRef = ref}
27
/>
28
</>
29
)
30
}
31
}
32
Web App
JavaScript
1
6
1
// register an event listener
2
window.addEventListener("message", message => {
3
console.log(message.data) // Wayne is coming!!!
4
window.ReactNativeWebView.postMessage('Client received data')
5
});
6