在React Native中从WebView检测按钮点击

7

你好,以下是关于如何在React Native中检测Webview按钮点击事件的翻译。在下面的代码中,我有一个WebView中的按钮(index.html),我想从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>
2个回答

12

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

首页.html

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

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

希望这有所帮助。


非常感谢您对此的回复,我也尝试过了,但没有成功。您能否提供一个可行的示例给我呢?我会非常感激的。 - user9081948
请查看此线程以了解与最新版本的兼容性。 - ketaki Damale

2

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函数的数据应为字符串

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接