I was trying to add a payment gateway using WebView flutter library.On successful completion of payment, the gateway redirects to a return url or webhook with transaction response. Now instead of redirection to some outside url, I want redirection to my app and want to read the status of transaction from response that is sent. All I want to know whether transaction is success or fail.
'''
WebView(
navigationDelegate: (action) {
return NavigationDecision.navigate;
},
onPageStarted: (url) => _onPageStart(url),
onPageFinished: (url) => _onPageFinish(url),
gestureNavigationEnabled: true,
debuggingEnabled: true,
javascriptMode: JavascriptMode.unrestricted,
initialUrl: url,
onWebViewCreated: (WebViewController webcontroller) {
_controller = webcontroller;
},
),
void _onPageStart(url) {
Future<String> future = _controller
.runJavascriptReturningResult("window.document.body.outerHTML");
future.then((data) {
print("ONpage start $data");
});
}
Future<void> _onPageFinish(url) async {
Future<String> future = _controller
.runJavascriptReturningResult("window.document.body.outerHTML");
future.then((data) {
print(data);
});
}
'''
What you have to do is simply add a javascript channel to your webview like this:
WebView(
onPageStarted: (url) => _onPageStart(url),
onPageFinished: (url) => _onPageFinish(URL),
gestureNavigationEnabled: true,
debuggingEnabled: true,
javascriptMode: JavascriptMode.unrestricted,
initialUrl: URL,
javascriptChannels: <JavascriptChannel>{
_toasterJavascriptChannel(context),
},
);
/*
create functionality on your web side also for this javascript channel
use the name 'Toaster' on the web side also ( use same name on web side and app side , name can be anything 'toaster' is example shown here)
*/
JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
return JavascriptChannel(
name: 'Toaster',
onMessageReceived: (JavascriptMessage message) {
// ignore: deprecated_member_use
Scaffold.of(context).showSnackBar(
SnackBar(content: Text(message.message)),
);
});
}
When you click on any function on the website, call this Toaster javascriptChannel on the web side and it will listen on the app side also