How can I redirect the phone dialer from WebView when I click on a phone number?

Viewed 65

I have implemented a custom web view renderer in Droid project. How can I redirect the Phone Dialer from WebView when I click on a phone number in WebView?

Any help is appreciated. Thanks!

1 Answers

You can try the following code:

 public class MyWebViewRenderer : WebViewRenderer
{
    public MyWebViewRenderer(Context context) : base(context) { }
    static MyWebView _xwebView = null;
    WebView _webView;
   
    class ExtendedWebViewClient : Android.Webkit.WebViewClient
    {
         public override bool ShouldOverrideUrlLoading(WebView view, string url)
        {
            var tel = "tel:";
            if (url != null)
            {
                if (url.StartsWith(tel))
                {

                    var uri = Android.Net.Uri.Parse(url);
                    var intent = new Intent(Intent.ActionView, uri);
                    intent.SetFlags(ActivityFlags.NewTask);
                    Android.App.Application.Context.StartActivity(intent);
                    return true;
                }
                
            }
            return false;
        }
    }

    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
    {
        base.OnElementChanged(e);
        _xwebView = e.NewElement as MyWebView;
        _webView = Control;

        if (e.OldElement == null)
        {
            _webView.SetWebViewClient(new ExtendedWebViewClient());
          
        }
    }

}

And for the ios part:

   public class MyWebViewRenderer : WkWebViewRenderer
{
    protected override void OnElementChanged(VisualElementChangedEventArgs e)
    {
        base.OnElementChanged(e);
        NavigationDelegate = new MyWKNavigationDelegate();
    }

    class MyWKNavigationDelegate : WKNavigationDelegate
    {

        [Export("webView:decidePolicyForNavigationAction:decisionHandler:")]
        public override void DecidePolicy(WKWebView webView, WKNavigationAction
        navigationAction, Action<WKNavigationActionPolicy> decisionHandler)
        {

            var navType = navigationAction.NavigationType;
            var targetFrame = navigationAction.TargetFrame;

            var url = navigationAction.Request.Url;
            if (
                url.ToString().StartsWith("http") && (targetFrame != null &&
            targetFrame.MainFrame == true)
                )
            {
                decisionHandler(WKNavigationActionPolicy.Allow);
            }
            else if (
                url.ToString().StartsWith("mailto:")
                || url.ToString().StartsWith("tel:")
                || url.ToString().StartsWith("Tel:"))
            {
                UIApplication.SharedApplication.application.OpenUrl(url);
            }

        }
    }
}
Related