Forum Xamarin.Forms

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

Webview open external browser

Hello all,
i'm using xamarin.forms webview to open a html page. So far so good.
Inside my html has "a href" linking to another URL and when clicked, its open inside the webview. I wanna open outside the webveiw, using the external browser (device broser). Any ideia?
Thanks a lot

Posts

  • MaxMengMaxMeng NZMember ✭✭✭
    edited April 2015

    Create an interface for DependencyService, say like IExternalBrowserService.

    public interface IExternalBrowserService
    {
        public void OpenUrl(string url);
    }
    

    In android, it would be like this:

    [assembly: Dependency(typeof(ExternalBrowserService))]
    namespace Your.Name.Space
    {
        public class ExternalBrowserService: IExternalBrowserService
        {
            public void OpenUrl(string url)
            {
                if(string.IsNullOrEmpty(url)) return;
    
                if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                    url = "http://" + url;
    
                var intent = new Intent(Intent.ActionView, Uri.Parse(url));
                intent.AddFlags(ActivityFlags.NewTask);
    
                Application.Context.StartActivity(intent);
            }
        }
    }
    

    For iOS, you can do same thing, sorry I don't have code.

    To use this:
    var service = DependencyService.Get<IExternalBrowserService>();
    service.OpenUrl("google.com");

  • MaxMengMaxMeng NZMember ✭✭✭

    That's a better answer, I don't event know there is already a method to handle this.

  • AndroidXamarinAndroidXamarin BRMember

    thanks guys! i resolved with adamkemp solution and it works !!! thanks a lot !

  • JohnHardmanJohnHardman GBUniversity admin

    @adamkemp - thanks for that snippet of code - very useful. Used almost as is (I also check for mailto: as a prefix).

  • SteveResnickSteveResnick USMember ✭✭

    Simple, clean, nice. Thanks!

  • How to first encrypt a web url and then open in browser in android?????????????

  • ChristineZuckermanChristineZuckerman USMember ✭✭✭

    @adamkemp I tried this approach but the e.url contains http even if my link doesn't. Has something changed?

  • adamkempadamkemp USInsider, Developer Group Leader mod

    I wouldn't know if something has changed because I don't work for Xamarin, and I don't know which versions of Xamarin.Forms you've tested or which OSes/versions you're testing. Also, what kind of links are you testing?

    FWIW, Xamarin.Forms is open source now so you can look at the code directly if needed.

  • DigilitiDevDigilitiDev USMember ✭✭
    edited August 2017

    Just a note on something that surprised me, it seems (on iOS only) the Navigating event is called when you first set Html property of HtmlWebViewSource. If your code is written such that that results in a call to e.Cancel, you'll end up with an empty WebView. Some kind of filtering like adamkemp has or something else is needed there so you don't e.Cancel the initial load.

  • HenriksenHenriksen NOMember ✭✭

    @DigilitiDev said:
    Just a note on something that surprised me, it seems (on iOS only) the Navigating event is called when you first set Html property of HtmlWebViewSource. If your code is written such that that results in a call to e.Cancel, you'll end up with an empty WebView. Some kind of filtering like adamkemp has or something else is needed there so you don't e.Cancel the initial load.

    This was a lifesaver for me yesterday! I had that very same issue and could not figure out why. Good call putting that note there.

  • ecorreaecorrea CLMember

    @adamkemp said:
    This is actually simpler. First, you can detect the navigation using an event on the web view called Navigating. Second, you can do the external navigation using Device.OpenUri. And then lastly you can cancel the web view's navigation. It would look like this:

            webview.Navigating += (s, e) =>
                {
                    if (e.Url.StartsWith("http"))
                    {
                        try
                        {
                            var uri = new Uri(e.Url);
                            Device.OpenUri(uri);
                        }
                        catch (Exception)
                        {
                        }
    
                        e.Cancel = true;
                    }
                };
    

    I put the StartsWith check in there to make it so that only external links go to the external browser. That allows for internal relative links to still work within the web view, which is a common pattern.

    this is the best and simplest solution that I found, thank you

  • YogeshhJunejaYogeshhJuneja INMember ✭✭
    edited January 2018

    i want to open browser and it redirect to another url with a value , get that value or url and close browser.. i am stucked since 3 days.. thanks in advance

  • FlachmannFlachmann Member
    edited December 2018

    Just to complete that. :) In my case, even using e.Cancel = true;, a blank page remained. So you have simply have to GoBack():

    private void WebViewGoBack(object sender, WebNavigatedEventArgs e)
    {
        (sender as WebView).GoBack();
    }
    

    But still I'd prefer if this step wouldn't be necessary and e.Cancel = true; would simply be enough. :'(

  • iMrTidyiMrTidy USMember ✭✭

    Works like a charm!

  • KhaiFMsiaKhaiFMsia Member ✭✭

    @adamkemp said:
    This is actually simpler. First, you can detect the navigation using an event on the web view called Navigating. Second, you can do the external navigation using Device.OpenUri. And then lastly you can cancel the web view's navigation. It would look like this:

            webview.Navigating += (s, e) =>
                {
                    if (e.Url.StartsWith("http"))
                    {
                        try
                        {
                            var uri = new Uri(e.Url);
                            Device.OpenUri(uri);
                        }
                        catch (Exception)
                        {
                        }
    
                        e.Cancel = true;
                    }
                };
    

    I put the StartsWith check in there to make it so that only external links go to the external browser. That allows for internal relative links to still work within the web view, which is a common pattern.

    Is this way can be done for iOS without any problem? Coz i thought iOS will block any redirect outside URL. Anyone can confirm this?

  • adamkempadamkemp USInsider, Developer Group Leader mod
    It definitely worked as of when I wrote that (I tested it), and I have no reason to think it doesn’t still work. As far as I know this is the right way to do this still.
  • KhaiFMsiaKhaiFMsia Member ✭✭

    @adamkemp thanks alot! :)

  • sumitmishrasumitmishra Member ✭✭✭

    Hi,
    Please guide me how to do that in xamarin.ios native app because we are not getting Navigating event. Please guide me to find a navigating link from webview and open it on external browser.

  • JohnHardmanJohnHardman GBUniversity admin

    @sumitmishra

    For Xamarin.iOS native app questions, post your questions in https://forums.xamarin.com/categories/ios , rather than re-awakening an old Xamarin.Forms thread

  • astralmasterastralmaster Member ✭✭

    In some cases when the HTML code that you load into the WebView contains an iframe or a twitter widget, the Navigating event will occur when the widget loads forcing you to go to twitter's website. How would one find a way around this? One solution is to check the Uri and filter out domain names but if you want to let users go to twitter's website when tapping a twitter widget it's no longer an option.

Sign In or Register to comment.