addJavaScriptHandler method
- required String handlerName,
- required JavaScriptHandlerCallback callback,
Adds a JavaScript message handler callback
(JavaScriptHandlerCallback) that listen to post messages sent from JavaScript by the handler with name handlerName
.
The Android implementation uses addJavascriptInterface. The iOS implementation uses addScriptMessageHandler
The JavaScript function that can be used to call the handler is window.flutter_inappwebview.callHandler(handlerName <String>, ...args)
, where args
are rest parameters.
The args
will be stringified automatically using JSON.stringify(args)
method and then they will be decoded on the Dart side.
In order to call window.flutter_inappwebview.callHandler(handlerName <String>, ...args)
properly, you need to wait and listen the JavaScript event flutterInAppWebViewPlatformReady
.
This event will be dispatched as soon as the platform (Android or iOS) is ready to handle the callHandler
method.
window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
console.log("ready");
});
window.flutter_inappwebview.callHandler
returns a JavaScript Promise
that can be used to get the json result returned by JavaScriptHandlerCallback.
In this case, simply return data that you want to send and it will be automatically json encoded using jsonEncode from the dart:convert
library.
So, on the JavaScript side, to get data coming from the Dart side, you will use:
<script>
window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
window.flutter_inappwebview.callHandler('handlerFoo').then(function(result) {
console.log(result);
});
window.flutter_inappwebview.callHandler('handlerFooWithArgs', 1, true, ['bar', 5], {foo: 'baz'}).then(function(result) {
console.log(result);
});
});
</script>
Instead, on the onLoadStop
WebView event, you can use callHandler
directly:
// Inject JavaScript that will receive data back from Flutter
inAppWebViewController.evaluateJavascript(source: """
window.flutter_inappwebview.callHandler('test', 'Text from Javascript').then(function(result) {
console.log(result);
});
""");
There could be forbidden names for JavaScript handlers depending on the implementation platform.
NOTE: This method should be called, for example, in the PlatformWebViewCreationParams.onWebViewCreated or PlatformWebViewCreationParams.onLoadStart events or, at least,
before you know that your JavaScript code will call the window.flutter_inappwebview.callHandler
method,
otherwise you won't be able to intercept the JavaScript message.
Officially Supported Platforms/Implementations:
- Android native WebView
- iOS
- MacOS
Implementation
void addJavaScriptHandler(
{required String handlerName,
required JavaScriptHandlerCallback callback}) {
throw UnimplementedError(
'addJavaScriptHandler is not implemented on the current platform');
}