Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to Handle (Tel:,Mailto:,Wa:,Sms:) In Inappwebview? #2

Open
dickynh2292 opened this issue Sep 27, 2021 · 2 comments
Open

How to Handle (Tel:,Mailto:,Wa:,Sms:) In Inappwebview? #2

dickynh2292 opened this issue Sep 27, 2021 · 2 comments

Comments

@dickynh2292
Copy link

dickynh2292 commented Sep 27, 2021

excuse me sir, permission to ask,
I'm just learning flutter and am trying to make an application using package _inappwebview & url_launcher,
Well, I'm having trouble trying to handle mailto, tel, etc.

Now when the link is clicked (eg href=tel:), it does exit the application but why does it go to the chrome browser (opens the webview url) instead of going to the phone.
Can anyone help me to tell where is my error?

My full code example can be seen here:


import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:permission_handler/permission_handler.dart';

void main() async {
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
    statusBarColor: Colors.white, // status bar color
    statusBarIconBrightness: Brightness.dark, // status bar icon color
    systemNavigationBarColor: Colors.white, // navigation bar color
    systemNavigationBarIconBrightness: Brightness.dark, // color of navigation controls
  ));
  WidgetsFlutterBinding.ensureInitialized();
  await Permission.camera.request();
  await Permission.microphone.request();
  await Permission.storage.request();
  await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
  await FlutterDownloader.initialize(debug: true);
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late InAppWebViewController webViewController;
  GlobalKey<ScaffoldState>webViewKey=GlobalKey<ScaffoldState>();

  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
      crossPlatform: InAppWebViewOptions(
        useShouldOverrideUrlLoading: true,
        mediaPlaybackRequiresUserGesture: false,
        javaScriptEnabled: true,
        javaScriptCanOpenWindowsAutomatically: true,
        useOnDownloadStart: true,
      ),
      android: AndroidInAppWebViewOptions(
        useHybridComposition: true,
      ),
      ios: IOSInAppWebViewOptions(
        allowsInlineMediaPlayback: true,
      )
  );

  late PullToRefreshController pullToRefreshController;
  String url = "";
  double progress = 0;
  final urlController = TextEditingController();

  @override
  void initState() {
    super.initState();
    pullToRefreshController = PullToRefreshController(
      options: PullToRefreshOptions(
        color: Colors.red,
      ),
      onRefresh: () async {
        if (Platform.isAndroid) {
          webViewController.reload();
        } else if (Platform.isIOS) {
          webViewController.loadUrl(
              urlRequest: URLRequest(url: await webViewController.getUrl()));
        }
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onBack,
      child: Scaffold(
          key: webViewKey,
          appBar: null,
          body: SafeArea(
              child: Column(children: <Widget>[
                Expanded(
                  child: Stack(
                    children: [
                      InAppWebView(
                        initialUrlRequest: URLRequest(url: Uri.parse("https://ummmah.com/")),
                        initialOptions: options,
                        pullToRefreshController: pullToRefreshController,
                        onWebViewCreated: (controller) {
                          webViewController = controller;
                        },
                        onLoadStart: (controller, url) {
                          setState(() {
                            this.url = url.toString();
                            urlController.text = this.url;
                          });
                        },
                        androidOnPermissionRequest: (controller, origin, resources) async {
                          return PermissionRequestResponse(
                              resources: resources,
                              action: PermissionRequestResponseAction.GRANT);
                        },
                        shouldOverrideUrlLoading: (controller, shouldOverrideUrlLoadingRequest) async {
                          var uri = shouldOverrideUrlLoadingRequest.request.url!;
                          if (uri.scheme.startsWith("tel")) {
                            if (await canLaunch(url)) {
                              await launch(
                                url,
                              );
                              return NavigationActionPolicy.CANCEL;
                            }
                          }
                          return NavigationActionPolicy.ALLOW;
                        },
                        onLoadStop: (controller, url) async {
                          pullToRefreshController.endRefreshing();
                          setState(() {
                            this.url = url.toString();
                            urlController.text = this.url;
                          });
                        },
                        onLoadError: (controller, url, code, message) {
                          pullToRefreshController.endRefreshing();
                        },
                        onProgressChanged: (controller, progress) {
                          if (progress == 100) {
                            pullToRefreshController.endRefreshing();
                          }
                          setState(() {
                            this.progress = progress / 100;
                            urlController.text = this.url;
                          });
                        },
                        onUpdateVisitedHistory: (controller, url, androidIsReload) {
                          setState(() {
                            this.url = url.toString();
                            urlController.text = this.url;
                          });
                        },
                        onConsoleMessage: (controller, consoleMessage) {
                          print(consoleMessage);
                        },
                      ),
                      progress < 1.0
                          ? LinearProgressIndicator(
                              value: progress,
                              minHeight: 2,
                          )
                          : Container(),
                    ],
                  ),
                ),
              ]
              )
          )
      ),
    );
  }
  Future<bool> _onBack() async {
    bool goBack;
    if (await webViewController.canGoBack()) {
      webViewController.goBack();
      return false;
    } else {
      showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text('Kamu yakin ingin keluar ?'),
            actions: <Widget>[
              FlatButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text('Tidak'),
              ),
              FlatButton(
                onPressed: () {
                  SystemNavigator.pop();
                },
                child: Text('Iya'),
              ),
            ],
          ));
      return Future.value(true);
    }
  }
}

@omanrai
Copy link

omanrai commented Jan 27, 2024

body: InAppWebView(
initialUrlRequest: URLRequest(url: Uri.parse("YOUR_INITIAL_URL")),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
javaScriptEnabled: true,
// Other options...
),
),
onWebViewCreated: (controller) {
webView = controller;
},
onLoadStart: (controller, url) async {
// Handle loading start event
print("WebView is starting to load: $url");
},
shouldOverrideUrlLoading: (controller, navigationAction) async {
var uri = navigationAction.request.url!;

      // Check if the URL is for Gmail
      if (uri.host.contains('mail.google.com')) {
        // Open Gmail URL in the WebView
        return NavigationActionPolicy.ALLOW;
      }
      // Check if the URL is for Facebook
      else if (uri.host.contains('facebook.com')) {
        // Open Facebook URL in the WebView
        return NavigationActionPolicy.ALLOW;
      }


      // For any other URLs like tel, allow them to load in the WebView
      return NavigationActionPolicy.ALLOW;
    },
  ),

@techwithsam
Copy link
Owner

Thank you @omanrai

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants