evaluateJavascript method

Future evaluateJavascript({
  1. required String source,
  2. ContentWorld? contentWorld,
})

Evaluates JavaScript source code into the WebView and returns the result of the evaluation.

contentWorld, on iOS, it represents the namespace in which to evaluate the JavaScript source code. Instead, on Android, it will run the source code into an iframe, using eval(source); to get and return the result. This parameter doesn’t apply to changes you make to the underlying web content, such as the document’s DOM structure. Those changes remain visible to all scripts, regardless of which content world you specify. For more information about content worlds, see ContentWorld. Available on iOS 14.0+.

NOTE: This method shouldn't be called in the WebView.onWebViewCreated or WebView.onLoadStart events, because, in these events, the WebView is not ready to handle it yet. Instead, you should call this method, for example, inside the WebView.onLoadStop event or in any other events where you know the page is ready "enough".

Supported Platforms/Implementations:

Implementation

Future<dynamic> evaluateJavascript(
    {required String source, ContentWorld? contentWorld}) async {
  Map<String, dynamic> args = <String, dynamic>{};
  args.putIfAbsent('source', () => source);
  args.putIfAbsent('contentWorld', () => contentWorld?.toMap());
  var data = await _channel.invokeMethod('evaluateJavascript', args);
  if (data != null && defaultTargetPlatform == TargetPlatform.android) {
    try {
      // try to json decode the data coming from JavaScript
      // otherwise return it as it is.
      data = json.decode(data);
    } catch (e) {}
  }
  return data;
}