使用injectJavaScript在WebView中调用函数

时间:2018-02-23 18:53:35

标签: react-native

我一直在寻找injectJavaScript的例子。在GitHub上,我发现了一些,我想测试一下:

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

但我无法使其发挥作用。我想也许我不得不等待加载WebView,但仍然没有运气。

这是我的测试:

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) }
      />
    );
  }
}

是通过字符串和道具与WebView进行通信的唯一方法吗?无法与传递本机javascript对象的WebView方法进行通信?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

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',
  },
});