Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call functions inside WebView with injectJavaScript

Tags:

react-native

I've been looking for examples of injectJavaScript. On GitHub I found a few which, I guess for testing, do:

injectJavaScript={()=>'alert("Injected JS ")'}

But I can't make it work. I thought that perhaps I had to wait for the WebView to be loaded, but still no luck.

Here my test:

export default class App extends React.Component {
  constructor( props ){
    super( props );

    this.state = {
      loaded: false
    };
  }
  webviewDidLoad(){
    this.setState({loaded: true});
  }
  render() {
    return (
      <WebView
        source={ webview }
        injectJavaScript={ this.state.loaded ? ()=>'alert("Injected JS")' : null }
        onLoadEnd={ this.webviewDidLoad.bind(this) }
      />
    );
  }
}

Is the only way to communicate to the WebView through strings and props? No way to communicate with WebView methods passing native javascript objects?

Thanks for your help!

like image 932
Nuthinking Avatar asked Jan 30 '26 21:01

Nuthinking


1 Answers

import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  TouchableHighlight,
  WebView,
} from 'react-native';

let jsCode = `
    document.querySelector('#myContent').style.backgroundColor = 'blue';
`;

export default class App extends Component {
  render() {
    return (
      <View style={localStyles.viroContainer}>

        <WebView
          source={{ html: "<h1 id='myContent'>Hello</h1>" }}
          style={{ flex: 1 }}
          ref={webview => {this.myWebview = webview;}} 
          injectedJavaScript={jsCode}
          javaScriptEnabled={true}
        />

        <TouchableHighlight
          style={localStyles.overlayButton}
          onPress={this.sendMessageToWebView2}
          underlayColor="transparent">
          <Text>Send message to WebView</Text>
        </TouchableHighlight>

      </View>
    );
  }

  sendMessageToWebView2 = () => {
    console.log(this.myWebview);
       console.log(this);
    this.myWebview.injectJavaScript(`
            (function () {
             document.querySelector('body').style.backgroundColor = 'orange';
            })();
        `);
  };
}

var localStyles = StyleSheet.create({
  viroContainer: {
    flex: 1,
  },
  overlayButton: {
    position: 'absolute',
    bottom: 0,
    left: 110,
    height: 50,
    width: 150,
    paddingTop: 30,
    paddingBottom: 30,
    marginTop: 10,
    marginBottom: 10,
    backgroundColor: '#f0a0aa',
    borderRadius: 10,
    borderWidth: 2,
    borderColor: '#000',
  },
});
like image 178
robertjuh Avatar answered Feb 01 '26 18:02

robertjuh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!