在 React Native 中检测来自 WebView 的按钮点击

Detect button click from WebView in React Native

任何人都可以帮助我如何检测 React Native 中的 Webview 按钮单击事件吗?如下面的代码所示,我的 WebView (index.html) 中有一个 Button,我想为其检测来自 React Native 的点击事件并执行 onClick 方法。我尝试了多种方法,但未能成功。非常感谢。

我的MyApp.js

import React from 'react';
import { AppRegistry, View, WebView, StyleSheet} from 'react-native'

export default class MyApp extends React.Component {
onClick = () => {
  console.log('Button Clicked');
}
render() {
    return (
        <View style={styles.container}>
            <WebView
                style={styles.webView}
                source={require('./index.html')}/>
        </View>
    );
}
};

let styles = StyleSheet.create({
container: {
    flex: 1,
    backgroundColor: '#fff',
},
webView: {
    backgroundColor: '#fff',
    height: 350,
}
});

我的index.html

<html>
<body>
    <Button>Click Here</Button>
</body>
</html>

window.postMessage() 添加到您的页面文件并将 onMessage={this.onMessage} 添加到您的 React Native WebView 组件。

示例:

// index.html (Web)
...
<script>
  window.postMessage("Sending data from WebView");
</script>
...


// MyWebView.js (React Native)
<WebView>
...
<WebView
   ref="webview"
    onMessage={this.onMessage}
/>
  
onMessage(data) {
  //Prints out data that was passed.
  console.log(data);
}

编辑: 工作示例:

App.js

onMessage(m) {
 alert(m.nativeEvent.data);
}
render() {
  return(
    <WebView
      style={{ flex: 1 }}
      source={{uri: 'http://127.0.0.1:8877'}} //my localhost
      onMessage={m => this.onMessage(m)} 
    />
  );
}

index.html

<button>Send post message from web</button>

<script>
document.querySelector("button").onclick = function() {
  console.log("Send post message");
  window.postMessage("Hello React", "*");
}
</script>

希望对您有所帮助

window.postMessage 不适用于我当前的最新版本。并找到了许多其他解决方案,这些解决方案可能在某些版本中对某些人有效但对我无效。

看看我是怎么解决的 window.ReactNativeWebView.postMessage:

"react": "16.13.1",
"react-native": "0.63.3",
"react-native-webview": "^11.0.2",

注意:我使用的是 html 字符串而不是 url

<WebView
    bounces={false}
    showsHorizontalScrollIndicator={false}
    showsVerticalScrollIndicator={false}
    javaScriptEnabled={true}
    originWhitelist={['*']}
    source={{ html }}
    onLoadEnd={this.onLoadEnd}
    onError={this.onError}
    mixedContentMode={'never'} // security
    startInLoadingState={true} // when starting this component
    onMessage={onMessage}
    javaScriptEnabledAndroid={true}
/>
onMessage = (message: string) => {
    console.log('action result coming from the webview: ', message);
};

并且在 html 字符串中我添加了下面的脚本并为给定的 html buttona 标签设置了 onclick

...
<div>
    <button onclick="clickYourButton([PASS SOME STRING DATA HERE])">Click</button>
</div>
...
<script type="text/javascript">
    function clickYourButton(data) {
        setTimeout(function () {
            window.ReactNativeWebView.postMessage(data)
        }, 0) // *** here ***
    }
</script>
  • 要传递给 postMessage 函数的数据应该是 string