我正在使用html脚本显示某些模块。一切都非常完美,直到事件处理程序没有任何响应。如何在Web View中获取eventHandler的响应。我没有获取onSuccess,onError或onClose方法的任何日志。我正在使用react-native-webview。我尝试使用window.postMessage('onSuccess');并在onMessage上获取值
this.khaltiUI = `<html>
<head>
<script src="https://khalti.com/static/khalti-checkout.js"></script>
</head>
<body>
<script>
var config = {
// replace the publicKey with yours
"publicKey": "test_public_key_dc74e0fd57cb46cd93832aee0a390234",
"productIdentity": "1234567890",
"productName": "Dragon",
"productUrl": "http://gameofthrones.wikia.com/wiki/Dragons",
"eventHandler": {
onSuccess (payload) {
window.postMessage('onSuccess');
console.log(payload);
},
onError (error) {
window.postMessage('onError')
console.log(error);
},
onClose () {
window.postMessage('onClosed')
console.log('widget is closing');
}
}
};
var checkout = new KhaltiCheckout(config);
checkout.show({amount: 1000, mobile: 9800000000});
</script>
</body>
</html>`
并在本机webView组件中:
<WebView
source={{html: this.khaltiUI }}
originWhitelist={["*"]}
scalesPageToFit={false}
style={{position: 'absolute', top: 0, bottom: 0, right: 0, left: 0}}
onMessage={this.onMessage}
startInLoadingState ={true}
/>
onMessage(event){
console.log('Hello'); //got no any response
console.log(JSON.parse(event.nativeEvent.data));
console.log(event.nativeEvent.data);
}
答案 0 :(得分:0)
要将数据发布到网页,首先,您必须获得ref
中的WebView
:
<WebView
ref={(webView) => this.webView = webView}
onMessage={this.onMessage}
...
/>
然后发布一条消息,例如:
sendPostMessage() {
console.log("Sending post message");
this.webView.postMessage("Post message from react native");
}
答案 1 :(得分:0)
这是我用来从webview向本地发送数据的方法:
反应:
import React, { Component } from "react";
import { WebView } from "react-native-webview";
export default class App extends Component {
_bridge(event) {
if(event.nativeEvent.data == 'exit') {
BackHandler.exitApp();
}
}
render() {
return (
<WebView
style={{flex: 1}}
source={{ uri: "https://www.kende.com/" }}
onMessage={event => { this._bridge(event); }}
/>
);
}
}
html:
<script>
$( document ).ready(function() {
$('#exit').on('click', function(){
window.ReactNativeWebView.postMessage("exit");
});
});
</script>
<span id="exit">Exit</span>