Open external browser on tapping on link with target=_blank Xamarin Forms WebView Android

asked 2022-06-02T13:00:44.29+00:00
Dipannita Das 21 Reputation points

Webpage is getting loaded inside Xamarin forms webview, links with target="_blank" not working on android
<a href="https://www.badgeofownership.com/" target="_blank">badgeofownership.com</a>

I have created custom renderer as per this https://github.com/xamarin/Xamarin.Forms/issues/12917, it solves the issue, however I want all the links with target=_blank opens up external browser instead of within webview.

Please suggest

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
4,805 questions
No comments
{count} votes

Accepted answer
  1. answered 2022-06-03T06:12:15.807+00:00
    Leon Lu (Shanghai Wicresoft Co,.Ltd.) 41,411 Reputation points Microsoft Employee

    Hello,​

    You have set Control.Settings.SetSupportMultipleWindows(true);, you need to create a WebChromeClient as well, and open the browser in the OnCreateWindow method like following code.

       Control.SetWebChromeClient(new MyWebChormeClient());  
         
       internal class MyWebChormeClient : Android.Webkit.WebChromeClient  
           {  
               public override bool OnCreateWindow(Android.Webkit.WebView view, bool isDialog, bool isUserGesture, Message resultMsg)  
               {  
                   HitTestResult TestResult = view.GetHitTestResult();  
                   string data = TestResult.Extra;  
                   Context context = view.Context;  
                   var uri = Android.Net.Uri.Parse(data);  
                   Intent browserIntent = new Intent(Intent.ActionView, uri);  
                   context.StartActivity(browserIntent);  
         
                   return false;  
         
               }  
           }  
    

    Note: I test this <a> in local html. I get the result "file:///android_asset/%60https://www.badgeofownership.com/%60" from string data = TestResult.Extra; line, So I need to Substring with Regex by string startString="%60" and string endString="%60", You need to handle it by your usage environment.

       public string Substring(string text, string start, string end)  
               {  
                   Regex regex = new Regex("(?<=(" + start + "))[.\\s\\S]*?(?=(" + end + "))", RegexOptions.Multiline | RegexOptions.Singleline);  
                   return regex.Match(text).Value;  
               }  
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful