evalJavascript method

Future evalJavascript(
  1. String code, {
  2. bool wrapPromise = true,
  3. bool allowRepeat = true,
})

Implementation

Future<dynamic> evalJavascript(
  String code, {
  bool wrapPromise = true,
  bool allowRepeat = true,
}) async {
  // check if there's a same request loading
  if (!allowRepeat) {
    for (String i in _msgCompleters.keys) {
      String call = code.split('(')[0];
      if (i.contains(call)) {
        print('request $call loading');
        return _msgCompleters[i]!.future;
      }
    }
  }

  if (!wrapPromise) {
    final res =
        await _web!.webViewController.evaluateJavascript(source: code);
    return res;
  }

  final c = new Completer();

  final uid = getEvalJavascriptUID();
  final method = 'uid=$uid;${code.split('(')[0]}';
  _msgCompleters[method] = c;

  final script = '$code.then(function(res) {'
      '  console.log(JSON.stringify({ path: "$method", data: res }));'
      '}).catch(function(err) {'
      '  console.log(JSON.stringify({ path: "log", data: {call: "$method", error: err.message} }));'
      '});';
  _web!.webViewController.evaluateJavascript(source: script);

  return c.future;
}