Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute Javascript on WebView when clicking a button on React-Native

Let's say I have this View containing a WebView and a Cart button over the WebView

export default class App extends Component<{}> {
  constructor(props){
    super(props);
  }
  render() {
    return (
      <View style={styles.parent}>
          <WebView
            source={{uri: 'https://mywebsite.com'}} style={styles.fullScreen}
            injectedJavaScript={jsCode}
            javaScriptEnabledAndroid={true}
          />
          <View style={styles.floatView}>
            <Button
              title="Cart"
              onPress={toggleCart}
              color="black"
            />
          </View>
      </View>
    );
  }
}

And when the user click on the button I want to execute this function

const toggleCart = function() {
  let jsCode = "app.trigger('toggle:cart');";
  //execute javascript code on webView
}

Is it something possible to do on React-Native?

Thanks

like image 926
Sam Bellerose Avatar asked Mar 07 '23 17:03

Sam Bellerose


1 Answers

First get a reference to your webview and then do this:

this.webview.postMessage("Hello from RN");



//to get this data into webview

...
<script>
  document.addEventListener("message", function(data) {
    // call whatever function you need
  });
</script>
...
like image 92
Alexander Vitanov Avatar answered Mar 10 '23 10:03

Alexander Vitanov