in_app_webview_controller.dart 74.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
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:html/parser.dart' show parse;

Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
14
import 'context_menu.dart';
15 16 17
import 'types.dart';
import 'in_app_browser.dart';
import 'webview_options.dart';
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31
import 'headless_in_app_webview.dart';
import 'webview.dart';
import 'in_app_webview.dart';

///List of forbidden names for JavaScript handlers.
const javaScriptHandlerForbiddenNames = [
  "onLoadResource",
  "shouldInterceptAjaxRequest",
  "onAjaxReadyStateChange",
  "onAjaxProgress",
  "shouldInterceptFetchRequest",
  "onPrint",
  "androidKeyboardWorkaroundFocusoutEvent"
];
32 33 34 35 36 37 38 39 40

///Controls a WebView, such as an [InAppWebView] widget instance, a [HeadlessInAppWebView] instance or [InAppBrowser] WebView instance.
///
///If you are using the [InAppWebView] widget, an [InAppWebViewController] instance can be obtained by setting the [InAppWebView.onWebViewCreated]
///callback. Instead, if you are using an [InAppBrowser] instance, you can get it through the [InAppBrowser.webViewController] attribute.
class InAppWebViewController {
  WebView _webview;
  MethodChannel _channel;
  static MethodChannel _staticChannel =
41
      MethodChannel('com.pichillilorenzo/flutter_inappwebview_static');
42
  Map<String, JavaScriptHandlerCallback> javaScriptHandlersMap =
43
      HashMap<String, JavaScriptHandlerCallback>();
44 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 92 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

  // ignore: unused_field
  bool _isOpened = false;

  // ignore: unused_field
  dynamic _id;
  String _inAppBrowserUuid;
  InAppBrowser _inAppBrowser;

  ///Android controller that contains only android-specific methods
  AndroidInAppWebViewController android;

  ///iOS controller that contains only ios-specific methods
  IOSInAppWebViewController ios;

  InAppWebViewController(dynamic id, WebView webview) {
    this._id = id;
    this._channel =
        MethodChannel('com.pichillilorenzo/flutter_inappwebview_$id');
    this._channel.setMethodCallHandler(handleMethod);
    this._webview = webview;
    this.android = AndroidInAppWebViewController(this);
    this.ios = IOSInAppWebViewController(this);
  }

  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 "onHeadlessWebViewCreated":
        if (_webview != null && _webview is HeadlessInAppWebView)
          _webview.onWebViewCreated(this);
        break;
      case "onLoadStart":
        String url = call.arguments["url"];
        if (_webview != null && _webview.onLoadStart != null)
          _webview.onLoadStart(this, url);
        else if (_inAppBrowser != null) _inAppBrowser.onLoadStart(url);
        break;
      case "onLoadStop":
        String url = call.arguments["url"];
        if (_webview != null && _webview.onLoadStop != null)
          _webview.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 (_webview != null && _webview.onLoadError != null)
          _webview.onLoadError(this, url, code, message);
        else if (_inAppBrowser != null)
          _inAppBrowser.onLoadError(url, code, message);
        break;
      case "onLoadHttpError":
        String url = call.arguments["url"];
        int statusCode = call.arguments["statusCode"];
        String description = call.arguments["description"];
        if (_webview != null && _webview.onLoadHttpError != null)
          _webview.onLoadHttpError(this, url, statusCode, description);
        else if (_inAppBrowser != null)
          _inAppBrowser.onLoadHttpError(url, statusCode, description);
        break;
      case "onProgressChanged":
        int progress = call.arguments["progress"];
        if (_webview != null && _webview.onProgressChanged != null)
          _webview.onProgressChanged(this, progress);
        else if (_inAppBrowser != null)
          _inAppBrowser.onProgressChanged(progress);
        break;
      case "shouldOverrideUrlLoading":
        String url = call.arguments["url"];
        String method = call.arguments["method"];
        Map<String, String> headers =
123
            call.arguments["headers"]?.cast<String, String>();
124 125 126 127 128 129
        bool isForMainFrame = call.arguments["isForMainFrame"];
        bool androidHasGesture = call.arguments["androidHasGesture"];
        bool androidIsRedirect = call.arguments["androidIsRedirect"];
        int iosWKNavigationType = call.arguments["iosWKNavigationType"];

        ShouldOverrideUrlLoadingRequest shouldOverrideUrlLoadingRequest =
130 131 132 133 134 135 136 137 138
            ShouldOverrideUrlLoadingRequest(
                url: url,
                method: method,
                headers: headers,
                isForMainFrame: isForMainFrame,
                androidHasGesture: androidHasGesture,
                androidIsRedirect: androidIsRedirect,
                iosWKNavigationType:
                    IOSWKNavigationType.fromValue(iosWKNavigationType));
139 140 141

        if (_webview != null && _webview.shouldOverrideUrlLoading != null)
          return (await _webview.shouldOverrideUrlLoading(
142
                  this, shouldOverrideUrlLoadingRequest))
143 144 145
              ?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser
146
                  .shouldOverrideUrlLoading(shouldOverrideUrlLoadingRequest))
147 148 149 150 151
              ?.toMap();
        break;
      case "onConsoleMessage":
        String message = call.arguments["message"];
        ConsoleMessageLevel messageLevel =
152
            ConsoleMessageLevel.fromValue(call.arguments["messageLevel"]);
153
        ConsoleMessage consoleMessage =
154
            ConsoleMessage(message: message, messageLevel: messageLevel);
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
        if (_webview != null && _webview.onConsoleMessage != null)
          _webview.onConsoleMessage(this, consoleMessage);
        else if (_inAppBrowser != null)
          _inAppBrowser.onConsoleMessage(consoleMessage);
        break;
      case "onScrollChanged":
        int x = call.arguments["x"];
        int y = call.arguments["y"];
        if (_webview != null && _webview.onScrollChanged != null)
          _webview.onScrollChanged(this, x, y);
        else if (_inAppBrowser != null) _inAppBrowser.onScrollChanged(x, y);
        break;
      case "onDownloadStart":
        String url = call.arguments["url"];
        if (_webview != null && _webview.onDownloadStart != null)
          _webview.onDownloadStart(this, url);
        else if (_inAppBrowser != null) _inAppBrowser.onDownloadStart(url);
        break;
      case "onLoadResourceCustomScheme":
        String scheme = call.arguments["scheme"];
        String url = call.arguments["url"];
        if (_webview != null && _webview.onLoadResourceCustomScheme != null) {
          try {
            var response =
179
                await _webview.onLoadResourceCustomScheme(this, scheme, url);
180 181 182 183 184 185 186 187
            return (response != null) ? response.toJson() : null;
          } catch (error) {
            print(error);
            return null;
          }
        } else if (_inAppBrowser != null) {
          try {
            var response =
188
                await _inAppBrowser.onLoadResourceCustomScheme(scheme, url);
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
            return (response != null) ? response.toJson() : null;
          } catch (error) {
            print(error);
            return null;
          }
        }
        break;
      case "onCreateWindow":
        String url = call.arguments["url"];
        bool androidIsDialog = call.arguments["androidIsDialog"];
        bool androidIsUserGesture = call.arguments["androidIsUserGesture"];
        int iosWKNavigationType = call.arguments["iosWKNavigationType"];

        OnCreateWindowRequest onCreateWindowRequest = OnCreateWindowRequest(
            url: url,
            androidIsDialog: androidIsDialog,
            androidIsUserGesture: androidIsUserGesture,
            iosWKNavigationType:
207
                IOSWKNavigationType.fromValue(iosWKNavigationType));
208 209 210 211 212 213 214 215 216 217 218

        if (_webview != null && _webview.onCreateWindow != null)
          _webview.onCreateWindow(this, onCreateWindowRequest);
        else if (_inAppBrowser != null)
          _inAppBrowser.onCreateWindow(onCreateWindowRequest);
        break;
      case "onGeolocationPermissionsShowPrompt":
        String origin = call.arguments["origin"];
        if (_webview != null &&
            _webview.androidOnGeolocationPermissionsShowPrompt != null)
          return (await _webview.androidOnGeolocationPermissionsShowPrompt(
219
                  this, origin))
220 221 222
              ?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser
223
                  .androidOnGeolocationPermissionsShowPrompt(origin))
224 225 226 227 228 229 230 231 232
              ?.toMap();
        break;
      case "onGeolocationPermissionsHidePrompt":
        if (_webview != null &&
            _webview.androidOnGeolocationPermissionsHidePrompt != null)
          await _webview.androidOnGeolocationPermissionsHidePrompt(this);
        else if (_inAppBrowser != null)
          await _inAppBrowser.androidOnGeolocationPermissionsHidePrompt();
        break;
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
      case "shouldInterceptRequest":
        String url = call.arguments["url"];
        String method = call.arguments["method"];
        Map<String, String> headers =
            call.arguments["headers"]?.cast<String, String>();
        bool isForMainFrame = call.arguments["isForMainFrame"];
        bool hasGesture = call.arguments["hasGesture"];
        bool isRedirect = call.arguments["isRedirect"];

        var request = new WebResourceRequest(
            url: url,
            method: method,
            headers: headers,
            isForMainFrame: isForMainFrame,
            hasGesture: hasGesture,
            isRedirect: isRedirect);

        if (_webview != null && _webview.androidShouldInterceptRequest != null)
          return (await _webview.androidShouldInterceptRequest(this, request))
              ?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser.androidShouldInterceptRequest(request))
              ?.toMap();
        break;
      case "onRenderProcessUnresponsive":
        String url = call.arguments["url"];
        if (_webview != null &&
            _webview.androidOnRenderProcessUnresponsive != null)
          return (await _webview.androidOnRenderProcessUnresponsive(this, url))
              ?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser.androidOnRenderProcessUnresponsive(url))
              ?.toMap();
        break;
      case "onRenderProcessResponsive":
        String url = call.arguments["url"];
        if (_webview != null &&
            _webview.androidOnRenderProcessResponsive != null)
          return (await _webview.androidOnRenderProcessResponsive(this, url))
              ?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser.androidOnRenderProcessResponsive(url))
              ?.toMap();
        break;
      case "onRenderProcessGone":
        bool didCrash = call.arguments["didCrash"];
        RendererPriority rendererPriorityAtExit = RendererPriority.fromValue(
            call.arguments["rendererPriorityAtExit"]);
        var detail = RenderProcessGoneDetail(
            didCrash: didCrash, rendererPriorityAtExit: rendererPriorityAtExit);

        if (_webview != null && _webview.androidOnRenderProcessGone != null)
          _webview.androidOnRenderProcessGone(this, detail);
        else if (_inAppBrowser != null)
          _inAppBrowser.androidOnRenderProcessGone(detail);
        break;
      case "onFormResubmission":
        String url = call.arguments["url"];
        if (_webview != null && _webview.androidOnFormResubmission != null)
          return (await _webview.androidOnFormResubmission(this, url))?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser.androidOnFormResubmission(url))?.toMap();
        break;
      case "onScaleChanged":
        double oldScale = call.arguments["oldScale"];
        double newScale = call.arguments["newScale"];
        if (_webview != null && _webview.androidOnScaleChanged != null)
          _webview.androidOnScaleChanged(this, oldScale, newScale);
        else if (_inAppBrowser != null)
          _inAppBrowser.androidOnScaleChanged(oldScale, newScale);
        break;
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
      case "onJsAlert":
        String message = call.arguments["message"];
        if (_webview != null && _webview.onJsAlert != null)
          return (await _webview.onJsAlert(this, message))?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser.onJsAlert(message))?.toMap();
        break;
      case "onJsConfirm":
        String message = call.arguments["message"];
        if (_webview != null && _webview.onJsConfirm != null)
          return (await _webview.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 (_webview != null && _webview.onJsPrompt != null)
          return (await _webview.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 =
331
            SafeBrowsingThreat.fromValue(call.arguments["threatType"]);
332
        if (_webview != null && _webview.androidOnSafeBrowsingHit != null)
333 334
          return (await _webview.androidOnSafeBrowsingHit(
                  this, url, threatType))
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
              ?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser.androidOnSafeBrowsingHit(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 (_webview != null && _webview.onReceivedHttpAuthRequest != null)
          return (await _webview.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);
373 374
        if (_webview != null &&
            _webview.onReceivedServerTrustAuthRequest != null)
375
          return (await _webview.onReceivedServerTrustAuthRequest(
376
                  this, challenge))
377 378 379
              ?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser
380
                  .onReceivedServerTrustAuthRequest(challenge))
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
              ?.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 (_webview != null && _webview.onReceivedClientCertRequest != null)
          return (await _webview.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 (_webview != null && _webview.onFindResultReceived != null)
          _webview.onFindResultReceived(
              this, activeMatchOrdinal, numberOfMatches, isDoneCounting);
        else if (_inAppBrowser != null)
          _inAppBrowser.onFindResultReceived(
              activeMatchOrdinal, numberOfMatches, isDoneCounting);
        break;
      case "onPermissionRequest":
        String origin = call.arguments["origin"];
        List<String> resources = call.arguments["resources"].cast<String>();
        if (_webview != null && _webview.androidOnPermissionRequest != null)
          return (await _webview.androidOnPermissionRequest(
414
                  this, origin, resources))
415 416 417
              ?.toMap();
        else if (_inAppBrowser != null)
          return (await _inAppBrowser.androidOnPermissionRequest(
418
                  origin, resources))
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
              ?.toMap();
        break;
      case "onUpdateVisitedHistory":
        String url = call.arguments["url"];
        bool androidIsReload = call.arguments["androidIsReload"];
        if (_webview != null && _webview.onUpdateVisitedHistory != null)
          _webview.onUpdateVisitedHistory(this, url, androidIsReload);
        else if (_inAppBrowser != null)
          _inAppBrowser.onUpdateVisitedHistory(url, androidIsReload);
        return null;
      case "onWebContentProcessDidTerminate":
        if (_webview != null &&
            _webview.iosOnWebContentProcessDidTerminate != null)
          _webview.iosOnWebContentProcessDidTerminate(this);
        else if (_inAppBrowser != null)
          _inAppBrowser.iosOnWebContentProcessDidTerminate();
435
        break;
436 437 438 439 440
      case "onPageCommitVisible":
        String url = call.arguments["url"];
        if (_webview != null && _webview.onPageCommitVisible != null)
          _webview.onPageCommitVisible(this, url);
        else if (_inAppBrowser != null) _inAppBrowser.onPageCommitVisible(url);
441
        break;
442 443 444 445 446 447 448
      case "onDidReceiveServerRedirectForProvisionalNavigation":
        if (_webview != null &&
            _webview.iosOnDidReceiveServerRedirectForProvisionalNavigation !=
                null)
          _webview.iosOnDidReceiveServerRedirectForProvisionalNavigation(this);
        else if (_inAppBrowser != null)
          _inAppBrowser.iosOnDidReceiveServerRedirectForProvisionalNavigation();
449
        break;
450 451
      case "onLongPressHitTestResult":
        Map<dynamic, dynamic> hitTestResultMap =
452 453 454 455
            call.arguments["hitTestResult"];
        InAppWebViewHitTestResultType type =
            InAppWebViewHitTestResultType.fromValue(
                hitTestResultMap["type"].toInt());
456
        String extra = hitTestResultMap["extra"];
457 458
        InAppWebViewHitTestResult hitTestResult =
            InAppWebViewHitTestResult(type: type, extra: extra);
459 460 461 462 463 464

        if (_webview != null && _webview.onLongPressHitTestResult != null)
          _webview.onLongPressHitTestResult(this, hitTestResult);
        else if (_inAppBrowser != null)
          _inAppBrowser.onLongPressHitTestResult(hitTestResult);
        break;
465 466 467 468 469 470 471 472 473 474
      case "onCreateContextMenu":
        ContextMenu contextMenu;
        if (_webview != null && _webview.contextMenu != null) {
          contextMenu = _webview.contextMenu;
        } else if (_inAppBrowser != null && _inAppBrowser.contextMenu != null) {
          contextMenu = _inAppBrowser.contextMenu;
        }

        if (contextMenu != null && contextMenu.onCreateContextMenu != null) {
          Map<dynamic, dynamic> hitTestResultMap =
475 476 477 478
              call.arguments["hitTestResult"];
          InAppWebViewHitTestResultType type =
              InAppWebViewHitTestResultType.fromValue(
                  hitTestResultMap["type"].toInt());
479
          String extra = hitTestResultMap["extra"];
480 481
          InAppWebViewHitTestResult hitTestResult =
              InAppWebViewHitTestResult(type: type, extra: extra);
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

          contextMenu.onCreateContextMenu(hitTestResult);
        }
        break;
      case "onHideContextMenu":
        ContextMenu contextMenu;
        if (_webview != null && _webview.contextMenu != null) {
          contextMenu = _webview.contextMenu;
        } else if (_inAppBrowser != null && _inAppBrowser.contextMenu != null) {
          contextMenu = _inAppBrowser.contextMenu;
        }

        if (contextMenu != null && contextMenu.onHideContextMenu != null) {
          contextMenu.onHideContextMenu();
        }
        break;
      case "onContextMenuActionItemClicked":
        ContextMenu contextMenu;
        if (_webview != null && _webview.contextMenu != null) {
          contextMenu = _webview.contextMenu;
        } else if (_inAppBrowser != null && _inAppBrowser.contextMenu != null) {
          contextMenu = _inAppBrowser.contextMenu;
        }

        if (contextMenu != null) {
          int androidId = call.arguments["androidId"];
          String iosId = call.arguments["iosId"];
          String title = call.arguments["title"];

511 512
          ContextMenuItem menuItemClicked = ContextMenuItem(
              androidId: androidId, iosId: iosId, title: title, action: null);
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527

          for (var menuItem in contextMenu.menuItems) {
            if ((Platform.isAndroid && menuItem.androidId == androidId) ||
                (Platform.isIOS && menuItem.iosId == iosId)) {
              menuItemClicked = menuItem;
              menuItem?.action();
              break;
            }
          }

          if (contextMenu.onContextMenuActionItemClicked != null) {
            contextMenu.onContextMenuActionItemClicked(menuItemClicked);
          }
        }
        break;
528
      case "onEnterFullscreen":
529
        if (_webview != null && _webview.onEnterFullscreen != null)
530
          _webview.onEnterFullscreen(this);
531
        else if (_inAppBrowser != null) _inAppBrowser.onEnterFullscreen();
532 533
        break;
      case "onExitFullscreen":
534
        if (_webview != null && _webview.onExitFullscreen != null)
535
          _webview.onExitFullscreen(this);
536
        else if (_inAppBrowser != null) _inAppBrowser.onExitFullscreen();
537
        break;
538 539 540 541 542 543
      case "onCallJsHandler":
        String handlerName = call.arguments["handlerName"];
        // decode args to json
        List<dynamic> args = jsonDecode(call.arguments["args"]);

        switch (handlerName) {
544 545 546 547 548
          case "androidKeyboardWorkaroundFocusoutEvent":
            // android Workaround to hide the Keyboard when the user click outside
            // on something not focusable such as input or a textarea.
            SystemChannels.textInput.invokeMethod("TextInput.hide");
            break;
549 550 551 552 553 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 585 586 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 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 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
          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: initiatorType,
                url: url,
                startTime: startTime,
                duration: duration);

            if (_webview != null && _webview.onLoadResource != null)
              _webview.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"];
            AjaxRequestHeaders headers = AjaxRequestHeaders(argMap["headers"]);
            String responseType = argMap["responseType"];

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

            if (_webview != null && _webview.shouldInterceptAjaxRequest != null)
              return jsonEncode(
                  await _webview.shouldInterceptAjaxRequest(this, request));
            else if (_inAppBrowser != null)
              return jsonEncode(
                  await _inAppBrowser.shouldInterceptAjaxRequest(request));
            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"];
            AjaxRequestHeaders headers = AjaxRequestHeaders(argMap["headers"]);
            int readyState = argMap["readyState"];
            int status = argMap["status"];
            String responseURL = argMap["responseURL"];
            String responseType = argMap["responseType"];
            dynamic response = argMap["response"];
            String responseText = argMap["responseText"];
            String responseXML = argMap["responseXML"];
            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,
                response: response,
                responseText: responseText,
                responseXML: responseXML,
                statusText: statusText,
                responseHeaders: responseHeaders);

            if (_webview != null && _webview.onAjaxReadyStateChange != null)
              return jsonEncode(
                  await _webview.onAjaxReadyStateChange(this, request));
            else if (_inAppBrowser != null)
              return jsonEncode(
                  await _inAppBrowser.onAjaxReadyStateChange(request));
            return null;
          case "onAjaxProgress":
            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"];
            AjaxRequestHeaders headers = AjaxRequestHeaders(argMap["headers"]);
            int readyState = argMap["readyState"];
            int status = argMap["status"];
            String responseURL = argMap["responseURL"];
            String responseType = argMap["responseType"];
            dynamic response = argMap["response"];
            String responseText = argMap["responseText"];
            String responseXML = argMap["responseXML"];
            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"],
                total: eventMap["total"],
                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,
                response: response,
                responseText: responseText,
                responseXML: responseXML,
                statusText: statusText,
                responseHeaders: responseHeaders,
                event: event);

            if (_webview != null && _webview.onAjaxProgress != null)
              return jsonEncode(await _webview.onAjaxProgress(this, request));
            else if (_inAppBrowser != null)
              return jsonEncode(await _inAppBrowser.onAjaxProgress(request));
            return null;
          case "shouldInterceptFetchRequest":
            Map<dynamic, dynamic> argMap = args[0];
            String url = argMap["url"];
            String method = argMap["method"];
            Map<dynamic, dynamic> headers = argMap["headers"];
            Uint8List body = Uint8List.fromList(argMap["body"].cast<int>());
            String mode = argMap["mode"];
            FetchRequestCredential credentials =
707 708
                FetchRequest.createFetchRequestCredentialFromMap(
                    argMap["credentials"]);
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
            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);

730 731
            if (_webview != null &&
                _webview.shouldInterceptFetchRequest != null)
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
              return jsonEncode(
                  await _webview.shouldInterceptFetchRequest(this, request));
            else if (_inAppBrowser != null)
              return jsonEncode(
                  await _inAppBrowser.shouldInterceptFetchRequest(request));
            return null;
          case "onPrint":
            String url = args[0];
            if (_webview != null && _webview.onPrint != null)
              _webview.onPrint(this, url);
            else if (_inAppBrowser != null) _inAppBrowser.onPrint(url);
            return null;
        }

        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.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
762 763 764 765
  ///This is not always the same as the URL passed to [WebView.onLoadStart] because although the load for that URL has begun, the current page may not have changed.
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#getUrl()
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1415005-url
766 767 768 769 770 771
  Future<String> getUrl() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await _channel.invokeMethod('getUrl', args);
  }

  ///Gets the title for the current page.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
772 773 774
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#getTitle()
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1415015-title
775 776 777 778 779 780
  Future<String> getTitle() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await _channel.invokeMethod('getTitle', args);
  }

  ///Gets the progress for the current page. The progress value is between 0 and 100.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
781 782 783
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#getProgress()
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1415007-estimatedprogress
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
  Future<int> getProgress() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await _channel.invokeMethod('getProgress', args);
  }

  ///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 = "";
    InAppWebViewGroupOptions options = await getOptions();
    if (options != null && options.crossPlatform.javaScriptEnabled == true) {
      html = await evaluateJavascript(
          source: "window.document.getElementsByTagName('html')[0].outerHTML;");
      if (html != null && 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 =
814
            await (await htmlRequest.close()).transform(Utf8Decoder()).join();
815 816 817 818 819 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 856
      } catch (e) {
        print(e);
      }
    }
    return html;
  }

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

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

    var html = await getHtml();
    if (html.isEmpty) {
      return favicons;
    }

    var assetPathBase;

    if (webviewUrl.startsWith("file:///")) {
      var assetPathSplitted = webviewUrl.split("/flutter_assets/");
      assetPathBase = assetPathSplitted[0] + "/flutter_assets/";
    }

    // 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);
          }
          manifestUrl = ((assetPathBase == null)
857 858
                  ? url.scheme + "://" + url.host + "/"
                  : assetPathBase) +
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
              manifestUrl;
        }
        continue;
      }
      if (!attributes["rel"].contains("icon")) {
        continue;
      }
      favicons.addAll(_createFavicons(url, assetPathBase, attributes["href"],
          attributes["rel"], attributes["sizes"], false));
    }

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

    // try to get the manifest file
    HttpClientRequest manifestRequest;
    HttpClientResponse manifestResponse;
    bool manifestFound = false;
    if (manifestUrl == null) {
      manifestUrl = url.scheme + "://" + url.host + "/manifest.json";
    }
    try {
      manifestRequest = await client.getUrl(Uri.parse(manifestUrl));
      manifestResponse = await manifestRequest.close();
      manifestFound = manifestResponse.statusCode == 200 &&
          manifestResponse.headers.contentType?.mimeType == "application/json";
    } catch (e) {
      print("Manifest file not found: " + e.toString());
    }

    if (manifestFound) {
      Map<String, dynamic> manifest =
897
          json.decode(await manifestResponse.transform(Utf8Decoder()).join());
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
      if (manifest.containsKey("icons")) {
        for (Map<String, dynamic> icon in manifest["icons"]) {
          favicons.addAll(_createFavicons(url, assetPathBase, icon["src"],
              icon["rel"], icon["sizes"], true));
        }
      }
    }

    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)
923 924
              ? url.scheme + "://" + url.host + "/"
              : assetPathBase) +
925 926 927 928 929
          urlIcon;
    }
    if (isManifest) {
      rel = (sizes != null)
          ? urlSplitted[urlSplitted.length - 1]
930 931 932
              .replaceFirst("-" + sizes, "")
              .split(" ")[0]
              .split(".")[0]
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
          : 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;
  }

  ///Loads the given [url] with optional [headers] specified as a map from name to value.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
951 952 953
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#loadUrl(java.lang.String)
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1414954-load
954 955 956 957 958 959 960 961 962 963
  Future<void> loadUrl(
      {@required String url, Map<String, String> headers = const {}}) async {
    assert(url != null && url.isNotEmpty);
    Map<String, dynamic> args = <String, dynamic>{};
    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.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
964 965
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#postUrl(java.lang.String,%20byte[])
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
  Future<void> postUrl(
      {@required String url, @required Uint8List postData}) async {
    assert(url != null && url.isNotEmpty);
    assert(postData != null);
    Map<String, dynamic> args = <String, dynamic>{};
    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 default value is `"text/html"`.
  ///
  ///The [encoding] parameter specifies the encoding of the data. The default value is `"utf8"`.
  ///
  ///The [androidHistoryUrl] parameter is the URL to use as the history entry. The default value is `about:blank`. If non-null, this must be a valid URL. This parameter is used only on Android.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
983 984 985 986 987
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#loadDataWithBaseURL(java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String)
  ///**Official iOS API**:
  ///- https://developer.apple.com/documentation/webkit/wkwebview/1415004-loadhtmlstring
  ///- https://developer.apple.com/documentation/webkit/wkwebview/1415011-load
988 989
  Future<void> loadData(
      {@required String data,
990 991 992 993
      String mimeType = "text/html",
      String encoding = "utf8",
      String baseUrl = "about:blank",
      String androidHistoryUrl = "about:blank"}) async {
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
    assert(data != null);
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('data', () => data);
    args.putIfAbsent('mimeType', () => mimeType);
    args.putIfAbsent('encoding', () => encoding);
    args.putIfAbsent('baseUrl', () => baseUrl);
    args.putIfAbsent('historyUrl', () => androidHistoryUrl);
    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:
  ///    - assets/index.html
  ///    - assets/css/
  ///    - assets/images/
  ///
  ///...
  ///```
  ///Example of a `main.dart` file:
  ///```dart
  ///...
  ///inAppBrowser.loadFile("assets/index.html");
  ///...
  ///```
  Future<void> loadFile(
      {@required String assetFilePath,
1035
      Map<String, String> headers = const {}}) async {
1036 1037 1038 1039 1040 1041 1042 1043
    assert(assetFilePath != null && assetFilePath.isNotEmpty);
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('url', () => assetFilePath);
    args.putIfAbsent('headers', () => headers);
    await _channel.invokeMethod('loadFile', args);
  }

  ///Reloads the WebView.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1044 1045 1046
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#reload()
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1414969-reload
1047 1048 1049 1050 1051 1052
  Future<void> reload() async {
    Map<String, dynamic> args = <String, dynamic>{};
    await _channel.invokeMethod('reload', args);
  }

  ///Goes back in the history of the WebView.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1053 1054 1055
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#goBack()
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1414952-goback
1056 1057 1058 1059 1060 1061
  Future<void> goBack() async {
    Map<String, dynamic> args = <String, dynamic>{};
    await _channel.invokeMethod('goBack', args);
  }

  ///Returns a boolean value indicating whether the WebView can move backward.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1062 1063 1064
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#canGoBack()
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1414966-cangoback
1065 1066 1067 1068 1069 1070
  Future<bool> canGoBack() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await _channel.invokeMethod('canGoBack', args);
  }

  ///Goes forward in the history of the WebView.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1071 1072 1073
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#goForward()
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1414993-goforward
1074 1075 1076 1077 1078 1079
  Future<void> goForward() async {
    Map<String, dynamic> args = <String, dynamic>{};
    await _channel.invokeMethod('goForward', args);
  }

  ///Returns a boolean value indicating whether the WebView can move forward.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1080 1081 1082
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#canGoForward()
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1414962-cangoforward
1083 1084 1085 1086 1087 1088
  Future<bool> canGoForward() async {
    Map<String, dynamic> args = <String, dynamic>{};
    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.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1089 1090 1091
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#goBackOrForward(int)
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1414991-go
1092 1093 1094 1095 1096 1097 1098 1099 1100
  Future<void> goBackOrForward({@required int steps}) async {
    assert(steps != null);

    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('steps', () => steps);
    await _channel.invokeMethod('goBackOrForward', args);
  }

  ///Returns a boolean value indicating whether the WebView can go back or forward the given number of steps. Steps is negative if backward and positive if forward.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1101 1102
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#canGoBackOrForward(int)
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
  Future<bool> canGoBackOrForward({@required int steps}) async {
    assert(steps != null);

    Map<String, dynamic> args = <String, dynamic>{};
    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({@required WebHistoryItem historyItem}) async {
    await goBackOrForward(steps: historyItem.offset);
  }

  ///Check if the WebView instance is in a loading state.
  Future<bool> isLoading() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await _channel.invokeMethod('isLoading', args);
  }

  ///Stops the WebView from loading.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1123 1124 1125
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#stopLoading()
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1414981-stoploading
1126 1127 1128 1129 1130 1131
  Future<void> stopLoading() async {
    Map<String, dynamic> args = <String, dynamic>{};
    await _channel.invokeMethod('stopLoading', args);
  }

  ///Evaluates JavaScript code into the WebView and returns the result of the evaluation.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1132 1133 1134
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#evaluateJavascript(java.lang.String,%20android.webkit.ValueCallback%3Cjava.lang.String%3E)
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1415017-evaluatejavascript
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
  Future<dynamic> evaluateJavascript({@required String source}) async {
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('source', () => source);
    var data = await _channel.invokeMethod('evaluateJavascript', args);
    if (data != null && Platform.isAndroid) data = json.decode(data);
    return data;
  }

  ///Injects an external JavaScript file into the WebView from a defined url.
  Future<void> injectJavascriptFileFromUrl({@required String urlFile}) async {
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('urlFile', () => urlFile);
    await _channel.invokeMethod('injectJavascriptFileFromUrl', args);
  }

  ///Injects a JavaScript file into the WebView from the flutter assets directory.
  Future<void> injectJavascriptFileFromAsset(
      {@required String assetFilePath}) async {
    String source = await rootBundle.loadString(assetFilePath);
    await evaluateJavascript(source: source);
  }

  ///Injects CSS into the WebView.
  Future<void> injectCSSCode({@required String source}) async {
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('source', () => source);
    await _channel.invokeMethod('injectCSSCode', args);
  }

  ///Injects an external CSS file into the WebView from a defined url.
  Future<void> injectCSSFileFromUrl({@required String urlFile}) async {
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('urlFile', () => urlFile);
    await _channel.invokeMethod('injectStyleFile', args);
  }

  ///Injects a CSS file into the WebView from the flutter assets directory.
  Future<void> injectCSSFileFromAsset({@required String assetFilePath}) async {
    String source = await rootBundle.loadString(assetFilePath);
    await injectCSSCode(source: source);
  }

  ///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_inappwebview.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_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.
  ///```javascript
  ///   window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
  ///     console.log("ready");
  ///   });
  ///```
  ///
  ///`window.flutter_inappwebview.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("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:
  ///```dart
  ///  // 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);
  ///    });
  ///  """);
  ///```
  ///
  ///Forbidden names for JavaScript handlers are defined in [javaScriptHandlerForbiddenNames].
  void addJavaScriptHandler(
      {@required String handlerName,
1225
      @required JavaScriptHandlerCallback callback}) {
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
    assert(!javaScriptHandlerForbiddenNames.contains(handlerName));
    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(
      {@required 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+.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1241 1242
  ///
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/2873260-takesnapshot
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
  Future<Uint8List> takeScreenshot() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await _channel.invokeMethod('takeScreenshot', args);
  }

  ///Sets the WebView options with the new [options] and evaluates them.
  Future<void> setOptions({@required InAppWebViewGroupOptions options}) async {
    Map<String, dynamic> args = <String, dynamic>{};

    args.putIfAbsent('options', () => options?.toMap());
    await _channel.invokeMethod('setOptions', args);
  }

  ///Gets the current WebView options. Returns the options with `null` value if they are not set yet.
  Future<InAppWebViewGroupOptions> getOptions() async {
    Map<String, dynamic> args = <String, dynamic>{};

    InAppWebViewGroupOptions inAppWebViewGroupOptions =
1261
        InAppWebViewGroupOptions();
1262
    Map<dynamic, dynamic> options =
1263
        await _channel.invokeMethod('getOptions', args);
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
    if (options != null) {
      options = options.cast<String, dynamic>();
      inAppWebViewGroupOptions.crossPlatform =
          InAppWebViewOptions.fromMap(options);
      if (Platform.isAndroid)
        inAppWebViewGroupOptions.android =
            AndroidInAppWebViewOptions.fromMap(options);
      else if (Platform.isIOS)
        inAppWebViewGroupOptions.ios = IOSInAppWebViewOptions.fromMap(options);
    }

    return inAppWebViewGroupOptions;
  }

  ///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.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1282 1283 1284
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#copyBackForwardList()
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1414977-backforwardlist
1285 1286 1287
  Future<WebHistory> getCopyBackForwardList() async {
    Map<String, dynamic> args = <String, dynamic>{};
    Map<dynamic, dynamic> result =
1288
        await _channel.invokeMethod('getCopyBackForwardList', args);
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
    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(
          originalUrl: historyItem["originalUrl"],
          title: historyItem["title"],
          url: historyItem["url"],
          index: i,
          offset: i - currentIndex));
    }
    return WebHistory(list: historyList, currentIndex: currentIndex);
  }

  ///Clears all the webview's cache.
  Future<void> clearCache() async {
    Map<String, dynamic> args = <String, dynamic>{};
    await _channel.invokeMethod('clearCache', 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.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1322 1323
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#findAllAsync(java.lang.String)
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
  Future<void> findAllAsync({@required String find}) async {
    assert(find != null);
    Map<String, dynamic> args = <String, dynamic>{};
    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.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1336 1337
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#findNext(boolean)
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
  Future<void> findNext({@required bool forward}) async {
    assert(forward != null);
    Map<String, dynamic> args = <String, dynamic>{};
    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.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1348 1349
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#clearMatches()
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
  Future<void> clearMatches() async {
    Map<String, dynamic> args = <String, dynamic>{};
    await _channel.invokeMethod('clearMatches', args);
  }

  ///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_inappwebview/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_inappwebview/t_rex_runner/t-rex.css");
  }

  ///Scrolls the WebView to the position.
  ///
  ///[x] represents the x position to scroll to.
  ///
  ///[y] represents the y position to scroll to.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1372 1373 1374
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/view/View#scrollTo(int,%20int)
  ///**Official iOS API**: https://developer.apple.com/documentation/uikit/uiscrollview/1619400-setcontentoffset
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
  Future<void> scrollTo({@required int x, @required int y}) async {
    assert(x != null && y != null);
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('x', () => x);
    args.putIfAbsent('y', () => y);
    await _channel.invokeMethod('scrollTo', args);
  }

  ///Moves the scrolled position of the WebView.
  ///
  ///[x] represents the amount of pixels to scroll by horizontally.
  ///
  ///[y] represents the amount of pixels to scroll by vertically.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1388 1389 1390
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/view/View#scrollBy(int,%20int)
  ///**Official iOS API**: https://developer.apple.com/documentation/uikit/uiscrollview/1619400-setcontentoffset
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
  Future<void> scrollBy({@required int x, @required int y}) async {
    assert(x != null && y != null);
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('x', () => x);
    args.putIfAbsent('y', () => y);
    await _channel.invokeMethod('scrollBy', args);
  }

  ///On Android, it pauses all layout, parsing, and JavaScript timers for all WebViews.
  ///This is a global requests, not restricted to just this WebView. This can be useful if the application has been paused.
  ///
  ///On iOS, it is restricted to just this WebView.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1403 1404
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#pauseTimers()
1405 1406 1407 1408 1409 1410 1411 1412
  Future<void> pauseTimers() async {
    Map<String, dynamic> args = <String, dynamic>{};
    await _channel.invokeMethod('pauseTimers', args);
  }

  ///On Android, it resumes all layout, parsing, and JavaScript timers for all WebViews. This will resume dispatching all timers.
  ///
  ///On iOS, it resumes all layout, parsing, and JavaScript timers to just this WebView.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1413 1414
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#resumeTimers()
1415 1416 1417 1418 1419 1420 1421 1422
  Future<void> resumeTimers() async {
    Map<String, dynamic> args = <String, dynamic>{};
    await _channel.invokeMethod('resumeTimers', args);
  }

  ///Prints the current page.
  ///
  ///**NOTE**: available on Android 21+.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1423 1424 1425
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/print/PrintManager
  ///**Official iOS API**: https://developer.apple.com/documentation/uikit/uiprintinteractioncontroller
1426 1427 1428 1429 1430 1431
  Future<void> printCurrentPage() async {
    Map<String, dynamic> args = <String, dynamic>{};
    await _channel.invokeMethod('printCurrentPage', args);
  }

  ///Gets the height of the HTML content.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1432 1433 1434
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#getContentHeight()
  ///**Official iOS API**: https://developer.apple.com/documentation/uikit/uiscrollview/1619399-contentsize
1435 1436 1437 1438 1439
  Future<int> getContentHeight() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await _channel.invokeMethod('getContentHeight', args);
  }

1440
  ///Performs a zoom operation in this WebView.
1441 1442 1443 1444
  ///
  ///[zoomFactor] represents the zoom factor to apply. On Android, the zoom factor will be clamped to the Webview's zoom limits and, also, this value must be in the range 0.01 to 100.0 inclusive.
  ///
  ///**NOTE**: available on Android 21+.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1445 1446 1447
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#zoomBy(float)
  ///**Official iOS API**: https://developer.apple.com/documentation/uikit/uiscrollview/1619412-setzoomscale
1448 1449 1450 1451 1452 1453 1454
  Future<void> zoomBy(double zoomFactor) async {
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('zoomFactor', () => zoomFactor);
    return await _channel.invokeMethod('zoomBy', args);
  }

  ///Gets the current scale of this WebView.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1455 1456 1457 1458 1459
  ///
  ///**Official Android API**:
  ///- https://developer.android.com/reference/android/util/DisplayMetrics#density
  ///- https://developer.android.com/reference/android/webkit/WebViewClient#onScaleChanged(android.webkit.WebView,%20float,%20float)
  ///**Official iOS API**: https://developer.apple.com/documentation/uikit/uiscrollview/1619419-zoomscale
1460 1461 1462 1463 1464
  Future<double> getScale() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await _channel.invokeMethod('getScale', args);
  }

1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
  ///Gets the selected text.
  ///
  ///**NOTE**: This method is implemented with using JavaScript.
  ///Available only on Android 19+.
  Future<String> getSelectedText() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await _channel.invokeMethod('getSelectedText', args);
  }

  ///Gets the hit result for hitting an HTML elements.
  ///
  ///**NOTE**: On iOS it is implemented using JavaScript.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1477 1478
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#getHitTestResult()
1479 1480
  Future<InAppWebViewHitTestResult> getHitTestResult() async {
    Map<String, dynamic> args = <String, dynamic>{};
1481 1482 1483 1484 1485
    var hitTestResultMap =
        await _channel.invokeMethod('getHitTestResult', args);
    InAppWebViewHitTestResultType type =
        InAppWebViewHitTestResultType.fromValue(
            hitTestResultMap["type"].toInt());
1486 1487 1488 1489
    String extra = hitTestResultMap["extra"];
    return InAppWebViewHitTestResult(type: type, extra: extra);
  }

1490
  ///Gets the default user agent.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1491 1492
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebSettings#getDefaultUserAgent(android.content.Context)
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
  static Future<String> getDefaultUserAgent() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await _staticChannel.invokeMethod('getDefaultUserAgent', args);
  }
}

///InAppWebViewControllerAndroid class represents the Android controller that contains only android-specific methods for the WebView.
class AndroidInAppWebViewController {
  InAppWebViewController _controller;

  AndroidInAppWebViewController(InAppWebViewController controller) {
    this._controller = controller;
  }

  ///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 on Android 27+.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1516 1517
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#startSafeBrowsing(android.content.Context,%20android.webkit.ValueCallback%3Cjava.lang.Boolean%3E)
1518 1519 1520 1521 1522 1523
  Future<bool> startSafeBrowsing() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await _controller._channel.invokeMethod('startSafeBrowsing', args);
  }

  ///Clears the SSL preferences table stored in response to proceeding with SSL certificate errors.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1524 1525
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#clearSslPreferences()
1526 1527 1528 1529 1530 1531 1532
  Future<void> clearSslPreferences() async {
    Map<String, dynamic> args = <String, dynamic>{};
    await _controller._channel.invokeMethod('clearSslPreferences', args);
  }

  ///Does a best-effort attempt to pause any processing that can be paused safely, such as animations and geolocation. Note that this call does not pause JavaScript.
  ///To pause JavaScript globally, use [pauseTimers()]. To resume WebView, call [resume()].
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1533 1534
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#onPause()
1535 1536 1537 1538 1539 1540
  Future<void> pause() async {
    Map<String, dynamic> args = <String, dynamic>{};
    await _controller._channel.invokeMethod('pause', args);
  }

  ///Resumes a WebView after a previous call to [pause()].
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1541 1542
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#onResume()
1543 1544 1545 1546 1547 1548 1549 1550
  Future<void> resume() async {
    Map<String, dynamic> args = <String, dynamic>{};
    await _controller._channel.invokeMethod('resume', args);
  }

  ///Gets the URL that was originally requested 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. Also, there may have been redirects resulting in a different URL to that originally requested.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1551 1552
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#getOriginalUrl()
1553 1554 1555 1556
  Future<String> getOriginalUrl() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await _controller._channel.invokeMethod('getOriginalUrl', args);
  }
1557

1558 1559 1560
  ///Scrolls the contents of this WebView down by half the page size.
  ///Returns `true` if the page was scrolled.
  ///
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1561 1562 1563
  ///[bottom] `true` to jump to bottom of page.
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#pageDown(boolean)
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
  Future<bool> pageDown({@required bool bottom}) async {
    assert(bottom != null);
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent("bottom", () => bottom);
    return await _controller._channel.invokeMethod('pageDown', args);
  }

  ///Scrolls the contents of this WebView up by half the view size.
  ///Returns `true` if the page was scrolled.
  ///
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1574 1575 1576
  ///[bottom] `true` to jump to the top of the page.
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#pageUp(boolean)
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
  Future<bool> pageUp({@required bool top}) async {
    assert(top != null);
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent("top", () => top);
    return await _controller._channel.invokeMethod('pageUp', args);
  }

  ///Saves the current view as a web archive.
  ///Returns the filename under which the file was saved, or `null` if saving the file failed.
  ///
  ///[basename] the filename where the archive should be placed. This value cannot be `null`.
  ///
  ///[autoname] if `false`, takes basename to be a file.
  ///If `true`, [basename] is assumed to be a directory in which a filename will be chosen according to the URL of the current page.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1591 1592
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#saveWebArchive(java.lang.String,%20boolean,%20android.webkit.ValueCallback%3Cjava.lang.String%3E)
1593 1594
  Future<String> saveWebArchive(
      {@required String basename, @required bool autoname}) async {
1595 1596 1597 1598 1599 1600 1601 1602 1603
    assert(basename != null && autoname != null);
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent("basename", () => basename);
    args.putIfAbsent("autoname", () => autoname);
    return await _controller._channel.invokeMethod('saveWebArchive', args);
  }

  ///Performs zoom in in this WebView.
  ///Returns `true` if zoom in succeeds, `false` if no zoom changes.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1604 1605
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#zoomIn()
1606 1607 1608 1609 1610 1611 1612
  Future<bool> zoomIn() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await _controller._channel.invokeMethod('zoomIn', args);
  }

  ///Performs zoom out in this WebView.
  ///Returns `true` if zoom out succeeds, `false` if no zoom changes.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1613 1614
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#zoomOut()
1615 1616 1617 1618 1619
  Future<bool> zoomOut() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await _controller._channel.invokeMethod('zoomOut', args);
  }

1620 1621 1622 1623 1624 1625 1626
  ///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 on Android 21+.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1627 1628
  ///
  ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#clearClientCertPreferences(java.lang.Runnable)
1629 1630
  static Future<void> clearClientCertPreferences() async {
    Map<String, dynamic> args = <String, dynamic>{};
1631 1632
    await InAppWebViewController._staticChannel
        .invokeMethod('clearClientCertPreferences', args);
1633 1634 1635 1636 1637
  }

  ///Returns a URL pointing to the privacy policy for Safe Browsing reporting. This value will never be `null`.
  ///
  ///**NOTE**: available only on Android 27+.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1638 1639
  ///
  ///**Official Android API**: https://developer.android.com/reference/androidx/webkit/WebViewCompat#getSafeBrowsingPrivacyPolicyUrl()
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
  static Future<String> getSafeBrowsingPrivacyPolicyUrl() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await InAppWebViewController._staticChannel
        .invokeMethod('getSafeBrowsingPrivacyPolicyUrl', 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 on Android 27+.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1661 1662
  ///
  ///**Official Android API**: https://developer.android.com/reference/androidx/webkit/WebViewCompat#getSafeBrowsingPrivacyPolicyUrl()
1663 1664
  static Future<bool> setSafeBrowsingWhitelist(
      {@required List<String> hosts}) async {
1665 1666 1667 1668 1669 1670
    assert(hosts != null);
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('hosts', () => hosts);
    return await InAppWebViewController._staticChannel
        .invokeMethod('setSafeBrowsingWhitelist', args);
  }
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680

  ///If WebView has already been loaded into the current process this method will return the package that was used to load it.
  ///Otherwise, the package that would be used if the WebView was loaded right now will be returned;
  ///this does not cause WebView to be loaded, so this information may become outdated at any time.
  ///The WebView package changes either when the current WebView package is updated, disabled, or uninstalled.
  ///It can also be changed through a Developer Setting. If the WebView package changes, any app process that
  ///has loaded WebView will be killed.
  ///The next time the app starts and loads WebView it will use the new WebView package instead.
  ///
  ///**NOTE**: available only on Android 26+.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1681 1682
  ///
  ///**Official Android API**: https://developer.android.com/reference/androidx/webkit/WebViewCompat#getCurrentWebViewPackage(android.content.Context)
1683 1684
  static Future<AndroidWebViewPackageInfo> getCurrentWebViewPackage() async {
    Map<String, dynamic> args = <String, dynamic>{};
1685 1686 1687 1688
    Map<String, dynamic> packageInfo = (await InAppWebViewController
            ._staticChannel
            .invokeMethod('getCurrentWebViewPackage', args))
        ?.cast<String, dynamic>();
1689 1690
    return AndroidWebViewPackageInfo.fromMap(packageInfo);
  }
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
}

///InAppWebViewControllerIOS class represents the iOS controller that contains only ios-specific methods for the WebView.
class IOSInAppWebViewController {
  InAppWebViewController _controller;

  IOSInAppWebViewController(InAppWebViewController controller) {
    this._controller = controller;
  }

  ///Reloads the current page, performing end-to-end revalidation using cache-validating conditionals if possible.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1702 1703
  ///
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1414956-reloadfromorigin
1704 1705 1706 1707 1708 1709
  Future<void> reloadFromOrigin() async {
    Map<String, dynamic> args = <String, dynamic>{};
    await _controller._channel.invokeMethod('reloadFromOrigin', args);
  }

  ///A Boolean value indicating whether all resources on the page have been loaded over securely encrypted connections.
Lorenzo Pichilli's avatar
Lorenzo Pichilli committed
1710 1711
  ///
  ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1415002-hasonlysecurecontent
1712 1713 1714 1715 1716 1717
  Future<bool> hasOnlySecureContent() async {
    Map<String, dynamic> args = <String, dynamic>{};
    return await _controller._channel
        .invokeMethod('hasOnlySecureContent', args);
  }
}