Reputation: 272
I am using the html script for showing some module. Everthing was going perfect until I got no any response of the eventHandler. How can I get the response of the eventHandler in Web View.I am not getting any log of the onSuccess, onError or onClose methods. I am using react-native-webview. I tried using window.postMessage('onSuccess'); and geting the value on 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>`
And in the react-native webView component:
<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);
}
Upvotes: 2
Views: 5675
Reputation: 843
this what I use for sending data from webview to react-native:
react:
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>
Upvotes: 3
Reputation: 571
To post data to a web page, first, you have to get the ref
of WebView
:
<WebView
ref={(webView) => this.webView = webView}
onMessage={this.onMessage}
...
/>
Then post a message like:
sendPostMessage() {
console.log("Sending post message");
this.webView.postMessage("Post message from react native");
}
Upvotes: 0