in_app_webview.dart 67.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
import 'dart:io';
import 'dart:async';
import 'dart:collection';
import 'dart:typed_data';
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/gestures.dart';

13 14
import 'package:html/parser.dart' show parse;

15 16 17 18
import 'types.dart';
import 'in_app_browser.dart';
import 'webview_options.dart';

19
const javaScriptHandlerForbiddenNames = ["onLoadResource", "shouldInterceptAjaxRequest", "onAjaxReadyStateChange", "onAjaxProgress", "shouldInterceptFetchRequest"];
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

///InAppWebView Widget class.
///
///Flutter Widget for adding an **inline native WebView** integrated in the flutter widget tree.
///
///All platforms support these options:
///  - __useShouldOverrideUrlLoading__: Set to `true` to be able to listen at the [InAppWebView.shouldOverrideUrlLoading()] event. The default value is `false`.
///  - __useOnLoadResource__: Set to `true` to be able to listen at the [InAppWebView.onLoadResource()] event. The default value is `false`.
///  - __useOnDownloadStart__: Set to `true` to be able to listen at the [InAppWebView.onDownloadStart()] event. The default value is `false`.
///  - __useOnTargetBlank__: Set to `true` to be able to listen at the [InAppWebView.onTargetBlank()] event. The default value is `false`.
///  - __clearCache__: Set to `true` to have all the browser's cache cleared before the new window is opened. The default value is `false`.
///  - __userAgent___: Set the custom WebView's user-agent.
///  - __javaScriptEnabled__: Set to `true` to enable JavaScript. The default value is `true`.
///  - __javaScriptCanOpenWindowsAutomatically__: Set to `true` to allow JavaScript open windows without user interaction. The default value is `false`.
///  - __mediaPlaybackRequiresUserGesture__: Set to `true` to prevent HTML5 audio or video from autoplaying. The default value is `true`.
///  - __transparentBackground__: Set to `true` to make the background of the WebView transparent. If your app has a dark theme, this can prevent a white flash on initialization. The default value is `false`.
///  - __resourceCustomSchemes__: List of custom schemes that [InAppWebView] must handle. Use the [InAppWebView.onLoadResourceCustomScheme()] event to intercept resource requests with custom scheme.
///
///  **Android** supports these additional options:
///
///  - __clearSessionCache__: Set to `true` to have the session cookie cache cleared before the new window is opened.
///  - __builtInZoomControls__: Set to `true` if the WebView should use its built-in zoom mechanisms. The default value is `false`.
///  - __displayZoomControls__: Set to `true` if the WebView should display on-screen zoom controls when using the built-in zoom mechanisms. The default value is `false`.
///  - __supportZoom__: Set to `false` if the WebView should not support zooming using its on-screen zoom controls and gestures. The default value is `true`.
44
///  - __databaseEnabled__: Set to `true` if you want injectScriptFilethe database storage API is enabled. The default value is `false`.
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
///  - __domStorageEnabled__: Set to `true` if you want the DOM storage API is enabled. The default value is `false`.
///  - __useWideViewPort__: Set to `true` if the WebView should enable support for the "viewport" HTML meta tag or should use a wide viewport. When the value of the setting is false, the layout width is always set to the width of the WebView control in device-independent (CSS) pixels. When the value is true and the page contains the viewport meta tag, the value of the width specified in the tag is used. If the page does not contain the tag or does not provide a width, then a wide viewport will be used. The default value is `true`.
///  - __safeBrowsingEnabled__: Set to `true` if you want the Safe Browsing is enabled. Safe Browsing allows WebView to protect against malware and phishing attacks by verifying the links. The default value is `true`.
///  - __textZoom__: Set text scaling of the WebView. The default value is `100`.
///  - __mixedContentMode__: Configures the WebView's behavior when a secure origin attempts to load a resource from an insecure origin. By default, apps that target `Build.VERSION_CODES.KITKAT` or below default to `MIXED_CONTENT_ALWAYS_ALLOW`. Apps targeting `Build.VERSION_CODES.LOLLIPOP` default to `MIXED_CONTENT_NEVER_ALLOW`. The preferred and most secure mode of operation for the WebView is `MIXED_CONTENT_NEVER_ALLOW` and use of `MIXED_CONTENT_ALWAYS_ALLOW` is strongly discouraged.
///
///  **iOS** supports these additional options:
///
///  - __disallowOverScroll__: Set to `true` to disable the bouncing of the WebView when the scrolling has reached an edge of the content. The default value is `false`.
///  - __enableViewportScale__: Set to `true` to allow a viewport meta tag to either disable or restrict the range of user scaling. The default value is `false`.
///  - __suppressesIncrementalRendering__: Set to `true` if you want the WebView suppresses content rendering until it is fully loaded into memory.. The default value is `false`.
///  - __allowsAirPlayForMediaPlayback__: Set to `true` to allow AirPlay. The default value is `true`.
///  - __allowsBackForwardNavigationGestures__: Set to `true` to allow the horizontal swipe gestures trigger back-forward list navigations. The default value is `true`.
///  - __allowsLinkPreview__: Set to `true` to allow that pressing on a link displays a preview of the destination for the link. The default value is `true`.
///  - __ignoresViewportScaleLimits__: Set to `true` if you want that the WebView should always allow scaling of the webpage, regardless of the author's intent. The ignoresViewportScaleLimits property overrides the `user-scalable` HTML property in a webpage. The default value is `false`.
///  - __allowsInlineMediaPlayback__: Set to `true` to allow HTML5 media playback to appear inline within the screen layout, using browser-supplied controls rather than native controls. For this to work, add the `webkit-playsinline` attribute to any `<video>` elements. The default value is `false`.
///  - __allowsPictureInPictureMediaPlayback__: Set to `true` to allow HTML5 videos play picture-in-picture. The default value is `true`.
class InAppWebView extends StatefulWidget {

  ///Event fires when the [InAppWebView] is created.
  final void Function(InAppWebViewController controller) onWebViewCreated;

  ///Event fires when the [InAppWebView] starts to load an [url].
  final void Function(InAppWebViewController controller, String url) onLoadStart;

  ///Event fires when the [InAppWebView] finishes loading an [url].
  final void Function(InAppWebViewController controller, String url) onLoadStop;

  ///Event fires when the [InAppWebView] encounters an error loading an [url].
  final void Function(InAppWebViewController controller, String url, int code, String message) onLoadError;

  ///Event fires when the current [progress] of loading a page is changed.
  final void Function(InAppWebViewController controller, int progress) onProgressChanged;

  ///Event fires when the [InAppWebView] receives a [ConsoleMessage].
  final void Function(InAppWebViewController controller, ConsoleMessage consoleMessage) onConsoleMessage;

  ///Give the host application a chance to take control when a URL is about to be loaded in the current WebView.
  ///
  ///**NOTE**: In order to be able to listen this event, you need to set `useShouldOverrideUrlLoading` option to `true`.
  final void Function(InAppWebViewController controller, String url) shouldOverrideUrlLoading;

  ///Event fires when the [InAppWebView] loads a resource.
  ///
  ///**NOTE**: In order to be able to listen this event, you need to set `useOnLoadResource` option to `true`.
  ///
  ///**NOTE only for Android**: to be able to listen this event, you need also the enable javascript.
92
  final void Function(InAppWebViewController controller, LoadedResource resource) onLoadResource;
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177

  ///Event fires when the [InAppWebView] scrolls.
  ///
  ///[x] represents the current horizontal scroll origin in pixels.
  ///
  ///[y] represents the current vertical scroll origin in pixels.
  final void Function(InAppWebViewController controller, int x, int y) onScrollChanged;

  ///Event fires when [InAppWebView] recognizes and starts a downloadable file.
  ///
  ///[url] represents the url of the file.
  final void Function(InAppWebViewController controller, String url) onDownloadStart;

  ///Event fires when the [InAppWebView] finds the `custom-scheme` while loading a resource. Here you can handle the url request and return a [CustomSchemeResponse] to load a specific resource encoded to `base64`.
  ///
  ///[scheme] represents the scheme of the url.
  ///
  ///[url] represents the url of the request.
  final Future<CustomSchemeResponse> Function(InAppWebViewController controller, String scheme, String url) onLoadResourceCustomScheme;

  ///Event fires when the [InAppWebView] tries to open a link with `target="_blank"`.
  ///
  ///[url] represents the url of the link.
  final void Function(InAppWebViewController controller, String url) onTargetBlank;

  ///Event that notifies the host application that web content from the specified origin is attempting to use the Geolocation API, but no permission state is currently set for that origin.
  ///Note that for applications targeting Android N and later SDKs (API level > `Build.VERSION_CODES.M`) this method is only called for requests originating from secure origins such as https.
  ///On non-secure origins geolocation requests are automatically denied.
  ///
  ///[origin] represents the origin of the web content attempting to use the Geolocation API.
  ///
  ///**NOTE**: available only for Android.
  final Future<GeolocationPermissionShowPromptResponse> Function(InAppWebViewController controller, String origin) onGeolocationPermissionsShowPrompt;

  ///Event fires when javascript calls the `alert()` method to display an alert dialog.
  ///If [JsAlertResponse.handledByClient] is `true`, the webview will assume that the client will handle the dialog.
  ///
  ///[message] represents the message to be displayed in the alert dialog.
  final Future<JsAlertResponse> Function(InAppWebViewController controller, String message) onJsAlert;

  ///Event fires when javascript calls the `confirm()` method to display a confirm dialog.
  ///If [JsConfirmResponse.handledByClient] is `true`, the webview will assume that the client will handle the dialog.
  ///
  ///[message] represents the message to be displayed in the alert dialog.
  final Future<JsConfirmResponse> Function(InAppWebViewController controller, String message) onJsConfirm;

  ///Event fires when javascript calls the `prompt()` method to display a prompt dialog.
  ///If [JsPromptResponse.handledByClient] is `true`, the webview will assume that the client will handle the dialog.
  ///
  ///[message] represents the message to be displayed in the alert dialog.
  ///
  ///[defaultValue] represents the default value displayed in the prompt dialog.
  final Future<JsPromptResponse> Function(InAppWebViewController controller, String message, String defaultValue) onJsPrompt;

  ///Event fires when the webview notifies that a loading URL has been flagged by Safe Browsing.
  ///The default behavior is to show an interstitial to the user, with the reporting checkbox visible.
  ///
  ///[url] represents the url of the request.
  ///
  ///[threatType] represents the reason the resource was caught by Safe Browsing, corresponding to a [SafeBrowsingThreat].
  ///
  ///**NOTE**: available only for Android.
  final Future<SafeBrowsingResponse> Function(InAppWebViewController controller, String url, SafeBrowsingThreat threatType) onSafeBrowsingHit;

  ///Event fires when a WebView received an HTTP authentication request. The default behavior is to cancel the request.
  ///
  ///[challenge] contains data about host, port, protocol, realm, etc. as specified in the auth challenge.
  final Future<HttpAuthResponse> Function(InAppWebViewController controller, HttpAuthChallenge challenge) onReceivedHttpAuthRequest;

  ///
  final Future<ServerTrustAuthResponse> Function(InAppWebViewController controller, ServerTrustChallenge challenge) onReceivedServerTrustAuthRequest;

  ///
  final Future<ClientCertResponse> Function(InAppWebViewController controller, ClientCertChallenge challenge) onReceivedClientCertRequest;

  ///Event fired as find-on-page operations progress.
  ///The listener may be notified multiple times while the operation is underway, and the numberOfMatches value should not be considered final unless [isDoneCounting] is true.
  ///
  ///[activeMatchOrdinal] represents the zero-based ordinal of the currently selected match.
  ///
  ///[numberOfMatches] represents how many matches have been found.
  ///
  ///[isDoneCounting] whether the find operation has actually completed.
  final void Function(InAppWebViewController controller, int activeMatchOrdinal, int numberOfMatches, bool isDoneCounting) onFindResultReceived;

178 179 180 181
  ///
  final Future<AjaxRequest> Function(InAppWebViewController controller, AjaxRequest ajaxRequest) shouldInterceptAjaxRequest;

  ///
182
  final Future<AjaxRequestAction> Function(InAppWebViewController controller, AjaxRequest ajaxRequest) onAjaxReadyStateChange;
183 184

  ///
185
  final Future<AjaxRequestAction> Function(InAppWebViewController controller, AjaxRequest ajaxRequest) onAjaxProgress;
186 187 188 189

  ///
  final Future<FetchRequest> Function(InAppWebViewController controller, FetchRequest fetchRequest) shouldInterceptFetchRequest;

190 191 192 193 194 195 196 197
  ///Event fired when the navigation state of the [InAppWebView] changes throught the usage of
  ///javascript **[History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API)** functions (`pushState()`, `replaceState()`) and `onpopstate` event.
  ///
  ///Also, the event is fired when the javascript `window.location` changes without reloading the webview (for example appending or modifying an hash to the url).
  ///
  ///[url] represents the new url.
  final void Function(InAppWebViewController controller, String url) onNavigationStateChange;

198 199 200 201 202 203 204 205 206
  ///Initial url that will be loaded.
  final String initialUrl;
  ///Initial asset file that will be loaded. See [InAppWebView.loadFile()] for explanation.
  final String initialFile;
  ///Initial [InAppWebViewInitialData] that will be loaded.
  final InAppWebViewInitialData initialData;
  ///Initial headers that will be used.
  final Map<String, String> initialHeaders;
  ///Initial options that will be used.
207
  final InAppWebViewWidgetOptions initialOptions;
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
  /// `gestureRecognizers` specifies which gestures should be consumed by the web view.
  /// It is possible for other gesture recognizers to be competing with the web view on pointer
  /// events, e.g if the web view is inside a [ListView] the [ListView] will want to handle
  /// vertical drags. The web view will claim gestures that are recognized by any of the
  /// recognizers on this list.
  /// When `gestureRecognizers` is empty or null, the web view will only handle pointer events for gestures that
  /// were not claimed by any other gesture recognizer.
  final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers;

  const InAppWebView({
    Key key,
    this.initialUrl = "about:blank",
    this.initialFile,
    this.initialData,
    this.initialHeaders = const {},
223
    this.initialOptions,
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
    this.onWebViewCreated,
    this.onLoadStart,
    this.onLoadStop,
    this.onLoadError,
    this.onConsoleMessage,
    this.onProgressChanged,
    this.shouldOverrideUrlLoading,
    this.onLoadResource,
    this.onScrollChanged,
    this.onDownloadStart,
    this.onLoadResourceCustomScheme,
    this.onTargetBlank,
    this.onGeolocationPermissionsShowPrompt,
    this.onJsAlert,
    this.onJsConfirm,
    this.onJsPrompt,
    this.onSafeBrowsingHit,
    this.onReceivedHttpAuthRequest,
    this.onReceivedServerTrustAuthRequest,
    this.onReceivedClientCertRequest,
    this.onFindResultReceived,
245 246
    this.shouldInterceptAjaxRequest,
    this.onAjaxReadyStateChange,
247
    this.onAjaxProgress,
248
    this.shouldInterceptFetchRequest,
249
    this.onNavigationStateChange,
250 251 252 253 254 255 256 257 258 259 260 261 262 263
    this.gestureRecognizers,
  }) : super(key: key);

  @override
  _InAppWebViewState createState() => _InAppWebViewState();
}

class _InAppWebViewState extends State<InAppWebView> {

  InAppWebViewController _controller;

  @override
  Widget build(BuildContext context) {
    Map<String, dynamic> initialOptions = {};
264 265 266 267 268
    initialOptions.addAll(widget.initialOptions.inAppWebViewOptions?.toMap() ?? {});
    if (Platform.isAndroid)
      initialOptions.addAll(widget.initialOptions.androidInAppWebViewOptions?.toMap() ?? {});
    else if (Platform.isIOS)
      initialOptions.addAll(widget.initialOptions.iosInAppWebViewOptions?.toMap() ?? {});
269 270

    if (defaultTargetPlatform == TargetPlatform.android) {
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
      return AndroidView(
        viewType: 'com.pichillilorenzo/flutter_inappwebview',
        onPlatformViewCreated: _onPlatformViewCreated,
        gestureRecognizers: widget.gestureRecognizers,
        layoutDirection: TextDirection.rtl,
        creationParams: <String, dynamic>{
          'initialUrl': widget.initialUrl,
          'initialFile': widget.initialFile,
          'initialData': widget.initialData?.toMap(),
          'initialHeaders': widget.initialHeaders,
          'initialOptions': initialOptions
        },
        creationParamsCodec: const StandardMessageCodec(),
      );
      // onLongPress issue: https://github.com/flutter/plugins/blob/f31d16a6ca0c4bd6849cff925a00b6823973696b/packages/webview_flutter/lib/src/webview_android.dart#L31
      /*return GestureDetector(
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
        onLongPress: () {},
        excludeFromSemantics: true,
        child: AndroidView(
          viewType: 'com.pichillilorenzo/flutter_inappwebview',
          onPlatformViewCreated: _onPlatformViewCreated,
          gestureRecognizers: widget.gestureRecognizers,
          layoutDirection: TextDirection.rtl,
          creationParams: <String, dynamic>{
            'initialUrl': widget.initialUrl,
            'initialFile': widget.initialFile,
            'initialData': widget.initialData?.toMap(),
            'initialHeaders': widget.initialHeaders,
            'initialOptions': initialOptions
          },
          creationParamsCodec: const StandardMessageCodec(),
        ),
303
      );*/
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
    } else if (defaultTargetPlatform == TargetPlatform.iOS) {
      return UiKitView(
        viewType: 'com.pichillilorenzo/flutter_inappwebview',
        onPlatformViewCreated: _onPlatformViewCreated,
        gestureRecognizers: widget.gestureRecognizers,
        creationParams: <String, dynamic>{
          'initialUrl': widget.initialUrl,
          'initialFile': widget.initialFile,
          'initialData': widget.initialData?.toMap(),
          'initialHeaders': widget.initialHeaders,
          'initialOptions': initialOptions
        },
        creationParamsCodec: const StandardMessageCodec(),
      );
    }
    return Text(
        '$defaultTargetPlatform is not yet supported by the flutter_inappbrowser plugin');
  }

  @override
  void didUpdateWidget(InAppWebView oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  void _onPlatformViewCreated(int id) {
    _controller = InAppWebViewController(id, widget);
    if (widget.onWebViewCreated != null) {
      widget.onWebViewCreated(_controller);
    }
  }
}

/// Controls an [InAppWebView] widget instance.
///
/// An [InAppWebViewController] instance can be obtained by setting the [InAppWebView.onWebViewCreated]
/// callback for an [InAppWebView] widget.
class InAppWebViewController {

  InAppWebView _widget;
  MethodChannel _channel;
  Map<String, JavaScriptHandlerCallback> javaScriptHandlersMap = HashMap<String, JavaScriptHandlerCallback>();
  bool _isOpened = false;
  // ignore: unused_field
  int _id;
  String _inAppBrowserUuid;
  InAppBrowser _inAppBrowser;


  InAppWebViewController(int id, InAppWebView widget) {
    this._id = id;
    this._channel = MethodChannel('com.pichillilorenzo/flutter_inappwebview_$id');
    this._channel.setMethodCallHandler(handleMethod);
    this._widget = widget;
  }

  InAppWebViewController.fromInAppBrowser(String uuid, MethodChannel channel, InAppBrowser inAppBrowser) {
    this._inAppBrowserUuid = uuid;
    this._channel = channel;
    this._inAppBrowser = inAppBrowser;
  }

  Future<dynamic> handleMethod(MethodCall call) async {
    switch(call.method) {
      case "onLoadStart":
        String url = call.arguments["url"];
        if (_widget != null && _widget.onLoadStart != null)
          _widget.onLoadStart(this, url);
        else if (_inAppBrowser != null)
          _inAppBrowser.onLoadStart(url);
        break;
      case "onLoadStop":
        String url = call.arguments["url"];
        if (_widget != null && _widget.onLoadStop != null)
          _widget.onLoadStop(this, url);
        else if (_inAppBrowser != null)
          _inAppBrowser.onLoadStop(url);
        break;
      case "onLoadError":
        String url = call.arguments["url"];
        int code = call.arguments["code"];
        String message = call.arguments["message"];
        if (_widget != null && _widget.onLoadError != null)
          _widget.onLoadError(this, url, code, message);
        else if (_inAppBrowser != null)
          _inAppBrowser.onLoadError(url, code, message);
        break;
      case "onProgressChanged":
        int progress = call.arguments["progress"];
        if (_widget != null && _widget.onProgressChanged != null)
          _widget.onProgressChanged(this, progress);
        else if (_inAppBrowser != null)
          _inAppBrowser.onProgressChanged(progress);
        break;
      case "shouldOverrideUrlLoading":
        String url = call.arguments["url"];
        if (_widget != null && _widget.shouldOverrideUrlLoading != null)
          _widget.shouldOverrideUrlLoading(this, url);
        else if (_inAppBrowser != null)
          _inAppBrowser.shouldOverrideUrlLoading(url);
        break;
      case "onConsoleMessage":
        String sourceURL = call.arguments["sourceURL"];
        int lineNumber = call.arguments["lineNumber"];
        String message = call.arguments["message"];
        ConsoleMessageLevel messageLevel = ConsoleMessageLevel.fromValue(call.arguments["messageLevel"]);
        if (_widget != null && _widget.onConsoleMessage != null)
          _widget.onConsoleMessage(this, ConsoleMessage(sourceURL, lineNumber, message, messageLevel));
        else if (_inAppBrowser != null)
          _inAppBrowser.onConsoleMessage(ConsoleMessage(sourceURL, lineNumber, message, messageLevel));
        break;
      case "onScrollChanged":
        int x = call.arguments["x"];
        int y = call.arguments["y"];
        if (_widget != null && _widget.onScrollChanged != null)
          _widget.onScrollChanged(this, x, y);
        else if (_inAppBrowser != null)
          _inAppBrowser.onScrollChanged(x, y);
        break;
      case "onDownloadStart":
        String url = call.arguments["url"];
        if (_widget != null && _widget.onDownloadStart != null)
          _widget.onDownloadStart(this, url);
        else if (_inAppBrowser != null)
          _inAppBrowser.onDownloadStart(url);
        break;
      case "onLoadResourceCustomScheme":
        String scheme = call.arguments["scheme"];
        String url = call.arguments["url"];
        if (_widget != null && _widget.onLoadResourceCustomScheme != null) {
          try {
            var response = await _widget.onLoadResourceCustomScheme(this, scheme, url);
            return (response != null) ? response.toJson(): null;
          } catch (error) {
            print(error);
            return null;
          }
        } else if (_inAppBrowser != null) {
          try {
            var response = await _inAppBrowser.onLoadResourceCustomScheme(scheme, url);
            return (response != null) ? response.toJson(): null;
          } catch (error) {
            print(error);
            return null;
          }
        }
        break;
      case "onTargetBlank":
        String url = call.arguments["url"];
        if (_widget != null && _widget.onTargetBlank != null)
          _widget.onTargetBlank(this, url);
        else if (_inAppBrowser != null)
          _inAppBrowser.onTargetBlank(url);
        break;
      case "onGeolocationPermissionsShowPrompt":
        String origin = call.arguments["origin"];
        if (_widget != null && _widget.onGeolocationPermissionsShowPrompt != null)
          return (await _widget.onGeolocationPermissionsShowPrompt(this, origin))?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser.onGeolocationPermissionsShowPrompt(origin))?.toMap();
        break;
      case "onJsAlert":
        String message = call.arguments["message"];
        if (_widget != null && _widget.onJsAlert != null)
          return (await _widget.onJsAlert(this, message))?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser.onJsAlert(message))?.toMap();
        break;
      case "onJsConfirm":
        String message = call.arguments["message"];
        if (_widget != null && _widget.onJsConfirm != null)
          return (await _widget.onJsConfirm(this, message))?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser.onJsConfirm(message))?.toMap();
        break;
      case "onJsPrompt":
        String message = call.arguments["message"];
        String defaultValue = call.arguments["defaultValue"];
        if (_widget != null && _widget.onJsPrompt != null)
          return (await _widget.onJsPrompt(this, message, defaultValue))?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser.onJsPrompt(message, defaultValue))?.toMap();
        break;
      case "onSafeBrowsingHit":
        String url = call.arguments["url"];
        SafeBrowsingThreat threatType = SafeBrowsingThreat.fromValue(call.arguments["threatType"]);
        if (_widget != null && _widget.onJsPrompt != null)
          return (await _widget.onSafeBrowsingHit(this, url, threatType))?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser.onSafeBrowsingHit(url, threatType))?.toMap();
        break;
      case "onReceivedHttpAuthRequest":
        String host = call.arguments["host"];
        String protocol = call.arguments["protocol"];
        String realm = call.arguments["realm"];
        int port = call.arguments["port"];
        int previousFailureCount = call.arguments["previousFailureCount"];
        var protectionSpace = ProtectionSpace(host: host, protocol: protocol, realm: realm, port: port);
        var challenge = HttpAuthChallenge(previousFailureCount: previousFailureCount, protectionSpace: protectionSpace);
        if (_widget != null && _widget.onReceivedHttpAuthRequest != null)
          return (await _widget.onReceivedHttpAuthRequest(this, challenge))?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser.onReceivedHttpAuthRequest(challenge))?.toMap();
        break;
      case "onReceivedServerTrustAuthRequest":
        String host = call.arguments["host"];
        String protocol = call.arguments["protocol"];
        String realm = call.arguments["realm"];
        int port = call.arguments["port"];
        int error = call.arguments["error"];
        String message = call.arguments["message"];
        Uint8List serverCertificate = call.arguments["serverCertificate"];
        var protectionSpace = ProtectionSpace(host: host, protocol: protocol, realm: realm, port: port);
        var challenge = ServerTrustChallenge(protectionSpace: protectionSpace, error: error, message: message, serverCertificate: serverCertificate);
        if (_widget != null && _widget.onReceivedServerTrustAuthRequest != null)
          return (await _widget.onReceivedServerTrustAuthRequest(this, challenge))?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser.onReceivedServerTrustAuthRequest(challenge))?.toMap();
        break;
      case "onReceivedClientCertRequest":
        String host = call.arguments["host"];
        String protocol = call.arguments["protocol"];
        String realm = call.arguments["realm"];
        int port = call.arguments["port"];
        var protectionSpace = ProtectionSpace(host: host, protocol: protocol, realm: realm, port: port);
        var challenge = ClientCertChallenge(protectionSpace: protectionSpace);
        if (_widget != null && _widget.onReceivedClientCertRequest != null)
          return (await _widget.onReceivedClientCertRequest(this, challenge))?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser.onReceivedClientCertRequest(challenge))?.toMap();
        break;
      case "onFindResultReceived":
        int activeMatchOrdinal = call.arguments["activeMatchOrdinal"];
        int numberOfMatches = call.arguments["numberOfMatches"];
        bool isDoneCounting = call.arguments["isDoneCounting"];
        if (_widget != null && _widget.onReceivedClientCertRequest != null)
          _widget.onFindResultReceived(this, activeMatchOrdinal, numberOfMatches, isDoneCounting);
        else if (_inAppBrowser != null)
          _inAppBrowser.onFindResultReceived(activeMatchOrdinal, numberOfMatches, isDoneCounting);
        break;
543 544 545 546 547 548 549
      case "onNavigationStateChange":
        String url = call.arguments["url"];
        if (_widget != null && _widget.onNavigationStateChange != null)
          _widget.onNavigationStateChange(this, url);
        else if (_inAppBrowser != null)
          _inAppBrowser.onNavigationStateChange(url);
        break;
550 551 552 553
      case "onCallJsHandler":
        String handlerName = call.arguments["handlerName"];
        // decode args to json
        List<dynamic> args = jsonDecode(call.arguments["args"]);
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584

        switch(handlerName) {
          case "onLoadResource":
            Map<dynamic, dynamic> argMap = args[0];
            String initiatorType = argMap["initiatorType"];
            String url = argMap["name"];
            double startTime = argMap["startTime"] is int ? argMap["startTime"].toDouble() : argMap["startTime"];
            double duration = argMap["duration"] is int ? argMap["duration"].toDouble() : argMap["duration"];

            var response = new LoadedResource(initiatorType, url, startTime, duration);

            if (_widget != null && _widget.onLoadResource != null)
              _widget.onLoadResource(this, response);
            else if (_inAppBrowser != null)
              _inAppBrowser.onLoadResource(response);
            return null;
          case "shouldInterceptAjaxRequest":
            Map<dynamic, dynamic> argMap = args[0];
            dynamic data = argMap["data"];
            String method = argMap["method"];
            String url = argMap["url"];
            bool isAsync = argMap["isAsync"];
            String user = argMap["user"];
            String password = argMap["password"];
            bool withCredentials = argMap["withCredentials"];
            Map<dynamic, dynamic> headers = argMap["headers"];

            var request = new AjaxRequest(data: data, method: method, url: url, isAsync: isAsync, user: user, password: password, withCredentials: withCredentials, headers: headers);

            if (_widget != null && _widget.shouldInterceptAjaxRequest != null)
              return jsonEncode(await _widget.shouldInterceptAjaxRequest(this, request));
585 586
            else if (_inAppBrowser != null)
              return jsonEncode(await _inAppBrowser.shouldInterceptAjaxRequest(request));
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
            return null;
          case "onAjaxReadyStateChange":
            Map<dynamic, dynamic> argMap = args[0];
            dynamic data = argMap["data"];
            String method = argMap["method"];
            String url = argMap["url"];
            bool isAsync = argMap["isAsync"];
            String user = argMap["user"];
            String password = argMap["password"];
            bool withCredentials = argMap["withCredentials"];
            Map<dynamic, dynamic> headers = argMap["headers"];
            int readyState = argMap["readyState"];
            int status = argMap["status"];
            String responseURL = argMap["responseURL"];
            String responseType = argMap["responseType"];
            String responseText = argMap["responseText"];
            String statusText = argMap["statusText"];
            Map<dynamic, dynamic> responseHeaders = argMap["responseHeaders"];

            var request = new AjaxRequest(data: data, method: method, url: url, isAsync: isAsync, user: user, password: password,
                withCredentials: withCredentials, headers: headers, readyState: AjaxRequestReadyState.fromValue(readyState), status: status, responseURL: responseURL,
                responseType: responseType, responseText: responseText, statusText: statusText, responseHeaders: responseHeaders);

            if (_widget != null && _widget.onAjaxReadyStateChange != null)
              return jsonEncode(await _widget.onAjaxReadyStateChange(this, request));
612 613
            else if (_inAppBrowser != null)
              return jsonEncode(await _inAppBrowser.onAjaxReadyStateChange(request));
614
            return null;
615
          case "onAjaxProgress":
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
            Map<dynamic, dynamic> argMap = args[0];
            dynamic data = argMap["data"];
            String method = argMap["method"];
            String url = argMap["url"];
            bool isAsync = argMap["isAsync"];
            String user = argMap["user"];
            String password = argMap["password"];
            bool withCredentials = argMap["withCredentials"];
            Map<dynamic, dynamic> headers = argMap["headers"];
            int readyState = argMap["readyState"];
            int status = argMap["status"];
            String responseURL = argMap["responseURL"];
            String responseType = argMap["responseType"];
            String responseText = argMap["responseText"];
            String statusText = argMap["statusText"];
            Map<dynamic, dynamic> responseHeaders = argMap["responseHeaders"];
            Map<dynamic, dynamic> eventMap = argMap["event"];

            AjaxRequestEvent event = AjaxRequestEvent(lengthComputable: eventMap["lengthComputable"], loaded: eventMap["loaded"], type: AjaxRequestEventType.fromValue(eventMap["type"]));

            var request = new AjaxRequest(data: data, method: method, url: url, isAsync: isAsync, user: user, password: password,
                withCredentials: withCredentials, headers: headers, readyState: AjaxRequestReadyState.fromValue(readyState), status: status, responseURL: responseURL,
                responseType: responseType, responseText: responseText, statusText: statusText, responseHeaders: responseHeaders, event: event);

640 641 642 643
            if (_widget != null && _widget.onAjaxProgress != null)
              return jsonEncode(await _widget.onAjaxProgress(this, request));
            else if (_inAppBrowser != null)
              return jsonEncode(await _inAppBrowser.onAjaxProgress(request));
644 645 646 647 648 649
            return null;
          case "shouldInterceptFetchRequest":
            Map<dynamic, dynamic> argMap = args[0];
            String url = argMap["url"];
            String method = argMap["method"];
            Map<dynamic, dynamic> headers = argMap["headers"];
650
            Uint8List body = Uint8List.fromList(argMap["body"].cast<int>());
651
            String mode = argMap["mode"];
652
            FetchRequestCredential credentials = FetchRequest.createFetchRequestCredentialFromMap(argMap["credentials"]);
653 654 655 656 657 658 659 660 661 662 663 664
            String cache = argMap["cache"];
            String redirect = argMap["redirect"];
            String referrer = argMap["referrer"];
            String referrerPolicy = argMap["referrerPolicy"];
            String integrity = argMap["integrity"];
            bool keepalive = argMap["keepalive"];

            var request = new FetchRequest(url: url, method: method, headers: headers, body: body, mode: mode, credentials: credentials,
                cache: cache, redirect: redirect, referrer: referrer, referrerPolicy: referrerPolicy, integrity: integrity, keepalive: keepalive);

            if (_widget != null && _widget.shouldInterceptFetchRequest != null)
              return jsonEncode(await _widget.shouldInterceptFetchRequest(this, request));
665 666
            else if (_inAppBrowser != null)
              return jsonEncode(await _inAppBrowser.shouldInterceptFetchRequest(request));
667 668 669
            return null;
        }

670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
        if (javaScriptHandlersMap.containsKey(handlerName)) {
          // convert result to json
          try {
            return jsonEncode(await javaScriptHandlersMap[handlerName](args));
          } catch (error) {
            print(error);
            return null;
          }
        }
        break;
      default:
        throw UnimplementedError("Unimplemented ${call.method} method");
    }
  }

  ///Gets the URL for the current page.
  ///This is not always the same as the URL passed to [InAppWebView.onLoadStarted] because although the load for that URL has begun, the current page may not have changed.
  Future<String> getUrl() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    return await _channel.invokeMethod('getUrl', args);
  }

  ///Gets the title for the current page.
  Future<String> getTitle() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    return await _channel.invokeMethod('getTitle', args);
  }

  ///Gets the progress for the current page. The progress value is between 0 and 100.
  Future<int> getProgress() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    return await _channel.invokeMethod('getProgress', args);
  }

716 717 718 719 720 721
  ///Gets the content html of the page. It first tries to get the content through javascript.
  ///If this doesn't work, it tries to get the content reading the file:
  ///- checking if it is an asset (`file:///`) or
  ///- downloading it using an `HttpClient` through the WebView's current url.
  Future<String> getHtml() async {
    var html = "";
722 723
    InAppWebViewWidgetOptions options = await getOptions();
    if (options != null && options.inAppWebViewOptions.javaScriptEnabled == true) {
724
      html = await evaluateJavascript("window.document.getElementsByTagName('html')[0].outerHTML;");
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
      if (html.isNotEmpty)
        return html;
    }

    var webviewUrl = await getUrl();
    if (webviewUrl.startsWith("file:///")) {
      var assetPathSplitted = webviewUrl.split("/flutter_assets/");
      var assetPath = assetPathSplitted[assetPathSplitted.length - 1];
      var bytes = await rootBundle.load(assetPath);
      html = utf8.decode(bytes.buffer.asUint8List());
    }
    else {
      HttpClient client = new HttpClient();
      var url = Uri.parse(webviewUrl);
      try {
        var htmlRequest = await client.getUrl(url);
        html = await (await htmlRequest.close()).transform(Utf8Decoder()).join();
      } catch (e) {
        print(e);
      }
    }
    return html;
  }

  ///Gets the list of all favicons for the current page.
  Future<List<Favicon>> getFavicons() async {
751
    List<Favicon> favicons = [];
752

753
    HttpClient client = new HttpClient();
754 755 756
    var webviewUrl = await getUrl();
    var url = (webviewUrl.startsWith("file:///")) ? Uri.file(webviewUrl) : Uri.parse(webviewUrl);
    String manifestUrl;
757

758 759 760 761
    var html = await getHtml();
    if (html.isEmpty) {
        return favicons;
    }
762

763 764 765 766 767
    var assetPathBase;

    if (webviewUrl.startsWith("file:///")) {
      var assetPathSplitted = webviewUrl.split("/flutter_assets/");
      assetPathBase = assetPathSplitted[0] + "/flutter_assets/";
768
    }
769 770 771 772 773 774 775 776 777 778 779

    // get all link html elements
    var document = parse(html);
    var links = document.getElementsByTagName('link');
    for (var link in links) {
      var attributes = link.attributes;
      if (attributes["rel"] == "manifest") {
        manifestUrl = attributes["href"];
        if (!_isUrlAbsolute(manifestUrl)) {
          if (manifestUrl.startsWith("/")) {
            manifestUrl = manifestUrl.substring(1);
780
          }
781
          manifestUrl = ((assetPathBase == null) ? url.scheme + "://" + url.host + "/" : assetPathBase) + manifestUrl;
782
        }
783
        continue;
784
      }
785 786 787 788 789
      if (!attributes["rel"].contains("icon")) {
        continue;
      }
      favicons.addAll(_createFavicons(url, assetPathBase, attributes["href"], attributes["rel"], attributes["sizes"], false));
    }
790

791
    // try to get /favicon.ico
792 793 794 795
    try {
      var faviconUrl = url.scheme + "://" + url.host + "/favicon.ico";
      await client.headUrl(Uri.parse(faviconUrl));
      favicons.add(Favicon(url: faviconUrl, rel: "shortcut icon"));
796 797 798
    } catch(e) {
      print("/favicon.ico file not found: " + e.toString());
    }
799

800 801 802 803 804 805 806
    // try to get the manifest file
    HttpClientRequest manifestRequest;
    HttpClientResponse manifestResponse;
    bool manifestFound = false;
    if (manifestUrl == null) {
      manifestUrl = url.scheme + "://" + url.host + "/manifest.json";
    }
807
    try {
808 809 810
      manifestRequest = await client.getUrl(Uri.parse(manifestUrl));
      manifestResponse = await manifestRequest.close();
      manifestFound = manifestResponse.statusCode == 200 && manifestResponse.headers.contentType?.mimeType == "application/json";
811
    } catch(e) {
812
      print("Manifest file not found: " + e.toString());
813 814
    }

815 816
    if (manifestFound) {
      Map<String, dynamic> manifest = json.decode(await manifestResponse.transform(Utf8Decoder()).join());
817 818
      if (manifest.containsKey("icons")) {
        for(Map<String, dynamic> icon in manifest["icons"]) {
819
          favicons.addAll(_createFavicons(url, assetPathBase, icon["src"], icon["rel"], icon["sizes"], true));
820 821 822 823
        }
      }
    }

824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
    return favicons;
  }

  bool _isUrlAbsolute(String url) {
    return url.startsWith("http://") || url.startsWith("https://");
  }

  List<Favicon> _createFavicons(Uri url, String assetPathBase, String urlIcon, String rel, String sizes, bool isManifest) {
    List<Favicon> favicons = [];

    List<String> urlSplitted = urlIcon.split("/");
    if (!_isUrlAbsolute(urlIcon)) {
      if (urlIcon.startsWith("/")) {
        urlIcon = urlIcon.substring(1);
      }
      urlIcon = ((assetPathBase == null) ? url.scheme + "://" + url.host + "/" : assetPathBase) + urlIcon;
    }
    if (isManifest) {
      rel = (sizes != null) ? urlSplitted[urlSplitted.length - 1].replaceFirst("-" + sizes, "").split(" ")[0].split(".")[0] : null;
    }
    if (sizes != null && sizes.isNotEmpty && sizes != "any") {
      List<String> sizesSplitted = sizes.split(" ");
      for (String size in sizesSplitted) {
        int width = int.parse(size.split("x")[0]);
        int height = int.parse(size.split("x")[1]);
        favicons.add(Favicon(url: urlIcon, rel: rel, width: width, height: height));
      }
    } else {
      favicons.add(Favicon(url: urlIcon, rel: rel, width: null, height: null));
    }

    return favicons;
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
  }

  ///Loads the given [url] with optional [headers] specified as a map from name to value.
  Future<void> loadUrl(String url, {Map<String, String> headers = const {}}) async {
    assert(url != null && url.isNotEmpty);
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened(message: 'Cannot laod $url!');
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    args.putIfAbsent('url', () => url);
    args.putIfAbsent('headers', () => headers);
    await _channel.invokeMethod('loadUrl', args);
  }

  ///Loads the given [url] with [postData] using `POST` method into this WebView.
  Future<void> postUrl(String url, Uint8List postData) async {
    assert(url != null && url.isNotEmpty);
    assert(postData != null);
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened(message: 'Cannot laod $url!');
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    args.putIfAbsent('url', () => url);
    args.putIfAbsent('postData', () => postData);
    await _channel.invokeMethod('postUrl', args);
  }

  ///Loads the given [data] into this WebView, using [baseUrl] as the base URL for the content.
  ///The [mimeType] parameter specifies the format of the data.
  ///The [encoding] parameter specifies the encoding of the data.
  Future<void> loadData(String data, {String mimeType = "text/html", String encoding = "utf8", String baseUrl = "about:blank"}) async {
    assert(data != null);
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    args.putIfAbsent('data', () => data);
    args.putIfAbsent('mimeType', () => mimeType);
    args.putIfAbsent('encoding', () => encoding);
    args.putIfAbsent('baseUrl', () => baseUrl);
    await _channel.invokeMethod('loadData', args);
  }

  ///Loads the given [assetFilePath] with optional [headers] specified as a map from name to value.
  ///
  ///To be able to load your local files (assets, js, css, etc.), you need to add them in the `assets` section of the `pubspec.yaml` file, otherwise they cannot be found!
  ///
  ///Example of a `pubspec.yaml` file:
  ///```yaml
  ///...
  ///
  ///# The following section is specific to Flutter.
  ///flutter:
  ///
  ///  # The following line ensures that the Material Icons font is
  ///  # included with your application, so that you can use the icons in
  ///  # the material Icons class.
  ///  uses-material-design: true
  ///
  ///  assets:
919
  ///    - assets/t-rex.html
920 921 922 923 924 925 926 927
  ///    - assets/css/
  ///    - assets/images/
  ///
  ///...
  ///```
  ///Example of a `main.dart` file:
  ///```dart
  ///...
928
  ///inAppBrowser.loadFile("assets/t-rex.html");
929 930 931 932 933 934 935 936 937 938 939 940 941 942
  ///...
  ///```
  Future<void> loadFile(String assetFilePath, {Map<String, String> headers = const {}}) async {
    assert(assetFilePath != null && assetFilePath.isNotEmpty);
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened(message: 'Cannot laod $assetFilePath!');
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    args.putIfAbsent('url', () => assetFilePath);
    args.putIfAbsent('headers', () => headers);
    await _channel.invokeMethod('loadFile', args);
  }

943
  ///Reloads the [InAppWebView].
944 945 946 947 948 949 950 951 952
  Future<void> reload() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    await _channel.invokeMethod('reload', args);
  }

953
  ///Goes back in the history of the [InAppWebView].
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
  Future<void> goBack() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    await _channel.invokeMethod('goBack', args);
  }

  ///Returns a boolean value indicating whether the [InAppWebView] can move backward.
  Future<bool> canGoBack() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    return await _channel.invokeMethod('canGoBack', args);
  }

973
  ///Goes forward in the history of the [InAppWebView].
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
  Future<void> goForward() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    await _channel.invokeMethod('goForward', args);
  }

  ///Returns a boolean value indicating whether the [InAppWebView] can move forward.
  Future<bool> canGoForward() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    return await _channel.invokeMethod('canGoForward', args);
  }

  ///Goes to the history item that is the number of steps away from the current item. Steps is negative if backward and positive if forward.
  Future<void> goBackOrForward(int steps) async {
    assert(steps != null);

    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    args.putIfAbsent('steps', () => steps);
    await _channel.invokeMethod('goBackOrForward', args);
  }

  ///Returns a boolean value indicating whether the [InAppWebView] can go back or forward the given number of steps. Steps is negative if backward and positive if forward.
  Future<bool> canGoBackOrForward(int steps) async {
    assert(steps != null);

    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    args.putIfAbsent('steps', () => steps);
    return await _channel.invokeMethod('canGoBackOrForward', args);
  }

  ///Navigates to a [WebHistoryItem] from the back-forward [WebHistory.list] and sets it as the current item.
  Future<void> goTo(WebHistoryItem historyItem) async {
    await goBackOrForward(historyItem.offset);
  }

  ///Check if the Web View of the [InAppWebView] instance is in a loading state.
  Future<bool> isLoading() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    return await _channel.invokeMethod('isLoading', args);
  }

  ///Stops the Web View of the [InAppWebView] instance from loading.
  Future<void> stopLoading() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    await _channel.invokeMethod('stopLoading', args);
  }

1044 1045
  ///Evaluates JavaScript code into the [InAppWebView] and returns the result of the evaluation.
  Future<String> evaluateJavascript(String source) async {
1046 1047 1048 1049 1050 1051
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    args.putIfAbsent('source', () => source);
1052
    return await _channel.invokeMethod('evaluateJavascript', args);
1053 1054
  }

1055 1056
  ///Injects an external JavaScript file into the [InAppWebView] from a defined url.
  Future<void> injectJavascriptFileFromUrl(String urlFile) async {
1057 1058 1059 1060 1061 1062
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    args.putIfAbsent('urlFile', () => urlFile);
1063 1064 1065 1066 1067 1068 1069
    await _channel.invokeMethod('injectJavascriptFileFromUrl', args);
  }
  
  ///Injects a JavaScript file into the [InAppWebView] from the flutter assets directory.
  Future<void> injectJavascriptFileFromAsset(String assetFilePath) async {
    String source = await rootBundle.loadString(assetFilePath);
    await evaluateJavascript(source);
1070 1071
  }

1072 1073
  ///Injects CSS into the [InAppWebView].
  Future<void> injectCSSCode(String source) async {
1074 1075 1076 1077 1078 1079
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    args.putIfAbsent('source', () => source);
1080
    await _channel.invokeMethod('injectCSSCode', args);
1081 1082
  }

1083 1084
  ///Injects an external CSS file into the [InAppWebView] from a defined url.
  Future<void> injectCSSFileFromUrl(String urlFile) async {
1085 1086 1087 1088 1089 1090 1091 1092 1093
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    args.putIfAbsent('urlFile', () => urlFile);
    await _channel.invokeMethod('injectStyleFile', args);
  }

1094 1095 1096 1097 1098 1099
  ///Injects a CSS file into the [InAppWebView] from the flutter assets directory.
  Future<void> injectCSSFileFromAsset(String assetFilePath) async {
    String source = await rootBundle.loadString(assetFilePath);
    await injectCSSCode(source);
  }

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
  ///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](https://developer.android.com/reference/android/webkit/WebView#addJavascriptInterface(java.lang.Object,%20java.lang.String)).
  ///The iOS implementation uses [addScriptMessageHandler](https://developer.apple.com/documentation/webkit/wkusercontentcontroller/1537172-addscriptmessagehandler?language=objc)
  ///
  ///The JavaScript function that can be used to call the handler is `window.flutter_inappbrowser.callHandler(handlerName <String>, ...args)`, where `args` are [rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/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_inappbrowser.callHandler(handlerName <String>, ...args)` properly, you need to wait and listen the JavaScript event `flutterInAppBrowserPlatformReady`.
  ///This event will be dispatch as soon as the platform (Android or iOS) is ready to handle the `callHandler` method.
  ///```javascript
  ///   window.addEventListener("flutterInAppBrowserPlatformReady", function(event) {
  ///     console.log("ready");
  ///   });
  ///```
  ///
  ///`window.flutter_inappbrowser.callHandler` returns a JavaScript [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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:
  ///```html
  ///<script>
  ///   window.addEventListener("flutterInAppBrowserPlatformReady", function(event) {
  ///     window.flutter_inappbrowser.callHandler('handlerFoo').then(function(result) {
  ///       console.log(result, typeof result);
  ///       console.log(JSON.stringify(result));
  ///     });
  ///
  ///     window.flutter_inappbrowser.callHandler('handlerFooWithArgs', 1, true, ['bar', 5], {foo: 'baz'}).then(function(result) {
  ///       console.log(result, typeof result);
  ///       console.log(JSON.stringify(result));
  ///     });
  ///   });
  ///</script>
  ///```
  ///
  ///Instead, on the `onLoadStop` WebView event, you can use `callHandler` directly:
  ///```dart
  ///  // Inject JavaScript that will receive data back from Flutter
  ///  inAppWebViewController.injectScriptCode("""
  ///    window.flutter_inappbrowser.callHandler('test', 'Text from Javascript').then(function(result) {
  ///      console.log(result);
  ///    });
  ///  """);
  ///```
  void addJavaScriptHandler(String handlerName, JavaScriptHandlerCallback callback) {
1147
    assert(!javaScriptHandlerForbiddenNames.contains(handlerName));
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
    this.javaScriptHandlersMap[handlerName] = (callback);
  }

  ///Removes a JavaScript message handler previously added with the [addJavaScriptHandler()] associated to [handlerName] key.
  ///Returns the value associated with [handlerName] before it was removed.
  ///Returns `null` if [handlerName] was not found.
  JavaScriptHandlerCallback removeJavaScriptHandler(String handlerName) {
    return this.javaScriptHandlersMap.remove(handlerName);
  }

  ///Takes a screenshot (in PNG format) of the WebView's visible viewport and returns a `Uint8List`. Returns `null` if it wasn't be able to take it.
  ///
  ///**NOTE for iOS**: available from iOS 11.0+.
  Future<Uint8List> takeScreenshot() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    return await _channel.invokeMethod('takeScreenshot', args);
  }

  ///Sets the [InAppWebView] options with the new [options] and evaluates them.
1171
  Future<void> setOptions(InAppWebViewWidgetOptions options) async {
1172 1173 1174 1175 1176
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
1177 1178 1179 1180 1181 1182 1183 1184 1185

    Map<String, dynamic> optionsMap = {};
    optionsMap.addAll(options.inAppWebViewOptions?.toMap() ?? {});
    if (Platform.isAndroid)
      optionsMap.addAll(options.androidInAppWebViewOptions?.toMap() ?? {});
    else if (Platform.isIOS)
      optionsMap.addAll(options.iosInAppWebViewOptions?.toMap() ?? {});

    args.putIfAbsent('options', () => optionsMap);
1186 1187 1188
    await _channel.invokeMethod('setOptions', args);
  }

1189 1190
  ///Gets the current [InAppWebView] options. Returns the options with `null` value if they are not set yet.
  Future<InAppWebViewWidgetOptions> getOptions() async {
1191 1192 1193 1194 1195
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
1196 1197

    InAppWebViewWidgetOptions inAppWebViewWidgetOptions = InAppWebViewWidgetOptions();
1198
    Map<dynamic, dynamic> options = await _channel.invokeMethod('getOptions', args);
1199
    if (options != null) {
1200
      options = options.cast<String, dynamic>();
1201 1202 1203 1204 1205 1206 1207 1208
      inAppWebViewWidgetOptions.inAppWebViewOptions = InAppWebViewOptions.fromMap(options);
      if (Platform.isAndroid)
        inAppWebViewWidgetOptions.androidInAppWebViewOptions = AndroidInAppWebViewOptions.fromMap(options);
      else if (Platform.isIOS)
        inAppWebViewWidgetOptions.iosInAppWebViewOptions = IosInAppWebViewOptions.fromMap(options);
    }

    return inAppWebViewWidgetOptions;
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
  }

  ///Gets the WebHistory for this WebView. This contains the back/forward list for use in querying each item in the history stack.
  ///This contains only a snapshot of the current state.
  ///Multiple calls to this method may return different objects.
  ///The object returned from this method will not be updated to reflect any new state.
  Future<WebHistory> getCopyBackForwardList() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    Map<dynamic, dynamic> result = await _channel.invokeMethod('getCopyBackForwardList', args);
    result = result.cast<String, dynamic>();

    List<dynamic> historyListMap = result["history"];
    historyListMap = historyListMap.cast<LinkedHashMap<dynamic, dynamic>>();

    int currentIndex = result["currentIndex"];

    List<WebHistoryItem> historyList = List();
    for(var i = 0; i < historyListMap.length; i++) {
      LinkedHashMap<dynamic, dynamic> historyItem = historyListMap[i];
      historyList.add(WebHistoryItem(historyItem["originalUrl"], historyItem["title"], historyItem["url"], i, i - currentIndex));
    }
    return WebHistory(historyList, currentIndex);
  }

  ///Starts Safe Browsing initialization.
  ///
  ///URL loads are not guaranteed to be protected by Safe Browsing until after the this method returns true.
  ///Safe Browsing is not fully supported on all devices. For those devices this method will returns false.
  ///
  ///This should not be called if Safe Browsing has been disabled by manifest tag
  ///or [AndroidInAppWebViewOptions.safeBrowsingEnabled]. This prepares resources used for Safe Browsing.
  ///
  ///**NOTE**: available only for Android.
  Future<bool> startSafeBrowsing() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    return await _channel.invokeMethod('startSafeBrowsing', args);
  }

  ///Sets the list of hosts (domain names/IP addresses) that are exempt from SafeBrowsing checks. The list is global for all the WebViews.
  ///
  /// Each rule should take one of these:
  ///| Rule | Example | Matches Subdomain |
  ///| -- | -- | -- |
  ///| HOSTNAME | example.com | Yes |
  ///| .HOSTNAME | .example.com | No |
  ///| IPV4_LITERAL | 192.168.1.1 | No |
  ///| IPV6_LITERAL_WITH_BRACKETS | [10:20:30:40:50:60:70:80] | No |
  ///
  ///All other rules, including wildcards, are invalid. The correct syntax for hosts is defined by [RFC 3986](https://tools.ietf.org/html/rfc3986#section-3.2.2).
  ///
  ///[hosts] represents the list of hosts. This value must never be null.
  ///
  ///**NOTE**: available only for Android.
  Future<bool> setSafeBrowsingWhitelist(List<String> hosts) async {
    assert(hosts != null);
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    args.putIfAbsent('hosts', () => hosts);
    return await _channel.invokeMethod('setSafeBrowsingWhitelist', args);
  }

  ///Returns a URL pointing to the privacy policy for Safe Browsing reporting. This value will never be `null`.
  ///
  ///**NOTE**: available only for Android.
  Future<String> getSafeBrowsingPrivacyPolicyUrl() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    return await _channel.invokeMethod('getSafeBrowsingPrivacyPolicyUrl', args);
  }

  ///Clears all the webview's cache
  Future<void> clearCache() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    await _channel.invokeMethod('clearCache', args);
  }

  ///Clears the SSL preferences table stored in response to proceeding with SSL certificate errors.
  ///
  ///**NOTE**: available only for Android.
  Future<void> clearSslPreferences() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    await _channel.invokeMethod('clearSslPreferences', args);
  }

  ///Clears the client certificate preferences stored in response to proceeding/cancelling client cert requests.
  ///Note that WebView automatically clears these preferences when the system keychain is updated.
  ///The preferences are shared by all the WebViews that are created by the embedder application.
  ///
  ///**NOTE**: On iOS certificate-based credentials are never stored permanently.
  ///
  ///**NOTE**: available only for Android.
  Future<void> clearClientCertPreferences() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    await _channel.invokeMethod('clearClientCertPreferences', args);
  }

  ///Finds all instances of find on the page and highlights them. Notifies [onFindResultReceived] listener.
  ///
  ///[find] represents the string to find.
  ///
  ///**NOTE**: on Android, it finds all instances asynchronously. Successive calls to this will cancel any pending searches.
  ///
  ///**NOTE**: on iOS, this is implemented using CSS and Javascript.
  Future<void> findAllAsync(String find) async {
    assert(find != null);
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    args.putIfAbsent('find', () => find);
    await _channel.invokeMethod('findAllAsync', args);
  }

  ///Highlights and scrolls to the next match found by [findAllAsync()]. Notifies [onFindResultReceived] listener.
  ///
  ///[forward] represents the direction to search.
  ///
  ///**NOTE**: on iOS, this is implemented using CSS and Javascript.
  Future<void> findNext(bool forward) async {
    assert(forward != null);
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    args.putIfAbsent('forward', () => forward);
    await _channel.invokeMethod('findNext', args);
  }

  ///Clears the highlighting surrounding text matches created by [findAllAsync()].
  ///
  ///**NOTE**: on iOS, this is implemented using CSS and Javascript.
  Future<void> clearMatches() async {
    Map<String, dynamic> args = <String, dynamic>{};
    if (_inAppBrowserUuid != null && _inAppBrowser != null) {
      _inAppBrowser.throwIsNotOpened();
      args.putIfAbsent('uuid', () => _inAppBrowserUuid);
    }
    await _channel.invokeMethod('clearMatches', args);
  }
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385

  ///Gets the html (with javascript) of the Chromium's t-rex runner game. Used in combination with [getTRexRunnerCss()].
  Future<String> getTRexRunnerHtml() async {
    return await rootBundle.loadString("packages/flutter_inappbrowser/t_rex_runner/t-rex.html");
  }

  ///Gets the css of the Chromium's t-rex runner game. Used in combination with [getTRexRunnerHtml()].
  Future<String> getTRexRunnerCss() async {
    return await rootBundle.loadString("packages/flutter_inappbrowser/t_rex_runner/t-rex.css");
  }
1386
}