如何通过单击本机按钮将数据发送到Webview

时间:2019-04-19 15:27:24

标签: javascript react-native webview

我使用了componentDidMount方法,该方法可以将数据正确发送到webview,但是当我单击特定的react native按钮时,我想发送数据webview。

在此webview中显示本地html页面,在此我将数据发送到webview,并且在html页面中发生加载事件时发出警报,该componentdidmount方法中的react native发送的数据成功地将数据发送至webview html页面但是当我在方法中尝试使用相同的代码时却说this.input未定义。

   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  >

)}

4 个答案:

答案 0 :(得分:1)

简而言之

Sending Data from Native(Webview) to Web App

// Native
this.webviewRef.postMessage('Wayne is coming!!!')

// Web
window.addEventListener("message", message => {
  console.log(message.data) // Wayne is coming!!!
});

Sending data from Web App to Native(Webview)

// Web App
<button onClick={() => {
  if(window.ReactNativeWebView) { // ensure window.ReactNativeWebView is there, otherwise, web app might crash if is not there
    window.ReactNativeWebView.postMessage('Wayne is coming again')
  }
}}>
</button>

// Native App
<WebView
  onMessage={(event) => {
    console.log(event.nativeEvent.data) // Client received data
  }}
  source={{ uri: 'https://your.domain.com' }}
/>

完整示例React本机代码

import React, { Component } from 'react';
import { WebView } from 'react-native-webview';
import { View, Button } from 'react-native';

class App extends Component {
  constructor(props) {
    super(props)
    this.webviewRef = null;
  }
  render() {
    return (
      <>
        <View style={{ flex: 1, alignContent: 'center', justifyContent: 'center' }}>
          <Button
            title="Press me"
            onPress={() => {
              this.webviewRef.postMessage('Wayne is coming!!!')
            }}
          />
        </View>
        <WebView
          onMessage={ (event) => {
            console.log(event.nativeEvent.data) // Client received data
          }}
          source={{ uri: 'https://your.domain.com' }}
          ref={ref => this.webviewRef = ref}
        />
      </>
    )
  }
}

网络应用

// register an event listener
window.addEventListener("message", message => {
  console.log(message.data) // Wayne is coming!!!
  window.ReactNativeWebView.postMessage('Client received data')
});

答案 1 :(得分:0)

您可以使用InjectionJavaScript做到这一点。只需在const中定义您的html页面源代码

class A {
    foo()
}
class B extends A{
    bar()
}

class C
{
    createA(): void
    get(): A
}

class D extends C{
    createA(): void //actually creates B
}

let d = new D();
d.createA();
let b = d.get();
b.bar(); //compiler error

并创建如下所示的方法

class C<T extends A>
{
    get(): T
}

class D extends C<B>{}

并在组件中返回这样的网络视图

const htmlData = require('./page.html');

就是这样!让我知道您是否还有任何疑问。

您的html文件如下所示。

injectedToHtml() {
    const myData = {planet: 'earth', galaxy: 'milkyway'};
    let injectedData = `document.getElementById('container').value = '${myData.planet+myData.galaxy}';`;
    return injectedData;
   }

答案 2 :(得分:0)

这是简单的代码,您可以在其中单击按钮将数据发送到WebView。

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

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

  sendDataToWebView() {
    let injectedData = `document.getElementById("login_field").value = 'example@github.com';`;
    this.webView.injectJavaScript(injectedData);
  }

  render() {
    return (
      <View style={{ flex: 1, marginTop: 35 }}>

        <TouchableHighlight style={{ padding: 10, backgroundColor: 'gray', marginTop: 20 }} onPress={() => this.sendDataToWebView()}>
          <Text style={{ color: 'white' }}>Send Data To WebView from React Native</Text>
        </TouchableHighlight>

        <WebView
          style={{ flex: 1 }}
          source={{ uri: 'https://github.com/login' }}
          ref={(webView) => this.webView = webView}

        />
      </View>
    );
  }
}

答案 3 :(得分:0)

不幸的是,不赞成使用postMessage()方法将数据从Native(Webview)发送到Web App的Web应用,而推荐使用injectJavaScript()

/**
 *  This script dispatches new custom messaging event
 */
function getInjectableJSMessage(message) {
  return `
    (function() {
      document.dispatchEvent(new MessageEvent('message', {
        data: ${JSON.stringify(message)}
      }));
    })();
  `;
}

// somewhere in your code
this.webviewRef.injectJavaScript(
    getInjectableJSMessage({
      message: 'Triggered event',
      triggeredAt: new Date(),
    })
);

在您的Web应用中,注册一个事件监听器

function handleEvent(message) {
   console.log(message.data);
}

// This will only work for Android
// https://stackoverflow.com/a/58118984
document.addEventListener("message", handleEvent);

查看相关的issue