initWebView method

Widget initWebView()

Implementation

Widget initWebView() {
  final Widget content;

  if (kIsWeb) {
    content = const SizedBox();
  } else {
    /// InAppWebView is a better choice for Android and iOS than official plugin for WebViews
    /// due to the possibility to manage ServerTrustAuthRequest, which is crucial in Android because Android
    /// native WebView does not allow to access an URL with a certificate not authorized by
    /// known certification authority.
    content = InAppWebView(
      // windowId: 12345,
      initialSettings: InAppWebViewSettings(
        useShouldOverrideUrlLoading: true,
        supportZoom: false,
        transparentBackground: true,

        /// This custom userAgent is mandatory due to security constraints of Google's OAuth2 policies (https://developers.googleblog.com/2021/06/upcoming-security-changes-to-googles-oauth-2.0-authorization-endpoint.html)
        userAgent: 'Mozilla/5.0',
        useHybridComposition: true,
      ),
      initialUrlRequest:
          URLRequest(url: WebUri(initialUri.toString()), headers: {
        ...configuration.headers,
        if (configuration.contentLocale != null)
          'Accept-Language': configuration.contentLocale!.toLanguageTag()
      }),
      onReceivedServerTrustAuthRequest: (controller, challenge) async {
        return ServerTrustAuthResponse(
            action: ServerTrustAuthResponseAction.PROCEED);
      },
      onWebViewCreated: (controller) {
        inAppWebViewController = controller;
      },
      shouldOverrideUrlLoading: (controller, navigationAction) async {
        final url = navigationAction.request.url?.toString() ?? '';
        return onNavigateTo(url)
            ? NavigationActionPolicy.ALLOW
            : NavigationActionPolicy.CANCEL;
      },
      onLoadStart: (controller, url) async {
        if (url == initialUri) {
          final certificate =
              (await controller.getCertificate())?.x509Certificate;
          if (certificate != null && !onCertificateValidate(certificate)) {
            onError(const CertificateException('Invalid certificate'));
          }
        }
        showLoading();
      },
      onLoadStop: (controller, url) async {
        hideLoading();
      },
      onReceivedError: (controller, request, error) => hideLoading(),
    );
  }

  return GestureDetector(
    onLongPressDown: (details) {},

    /// To avoid long press for text selection or open link on new tab
    child: content,
  );
}