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.
export default class HtmlRender extends Component { //error:this.input is undefined sendData() { this.input.postMessage( data ) } // This Is working componentDidMount(){ this.input.postMessage( data) } render(){ return ( <View style={styles.fullContainer}> <View style={styles.webviewBorder} > <WebView ref={(input) => this.input = input} source={{uri:'file:///android_asset/Page.html'}} /> </View> <View > <Button onPress={this.sendData}> <Text> Data </Text> </Button> </View> </View > )}
Answer
you can do it with injectedJavaScript. just define your html page source in const
const htmlData = require('./page.html');
and create a method like below
injectedToHtml() { const myData = {planet: 'earth', galaxy: 'milkyway'}; let injectedData = `document.getElementById('container').value = '${myData.planet+myData.galaxy}';`; return injectedData; }
and return your web view like this in your component
<WebView source={htmlData} javaScriptEnabled={true} injectedJavaScript={injectedToHtml()} style={{flex: 1}} />
that’s it! let me know if you still have any question.
your html file look like this..
<!DOCTYPE html> <html> <head> <style> #container { width:100%; height:100vh; display: flex; align-items:center; justify-content: center; } </style> </head> <body> <div id="container"></div> </body> </html>