Lucian
Lucian

Reputation: 49

How To Pass a Query String in Xamarin WebView Source On Navigating

I need to pass a query string into a WebView Xamarin Source on Navigating (www.websiteexmple.com?mobileapp=true).

In Android works perfect, but in IOS does not seems to work correctly sometimes . I am missing someting ?

I have notice it does not work in IOS when Net Core website needs to do some redirects : Ex: User Enter Email and click Next Step.

 public void WebView_NavigatingAsync(object sender, WebNavigatingEventArgs args)
    {
        if (!args.Url.Contains(Source) && !args.Url.Contains("facebook") && !args.Url.Contains("google"))
        {
            var uri = new Uri(args.Url);
            // Device.OpenUri(uri);
            Launcher.OpenAsync(uri);
            args.Cancel = true;
        }
        else
        {
            var src = args.Url;
            string prefix = "?";
            if (src.Contains("?"))
            {
                prefix = "&";
            }
            if (!args.Url.Contains("mobileapp=true"))
            {
                args.Cancel = true;
                var webview = (WebView)sender;
                webview.Source = src + prefix + "mobileapp=true";                   
            }
        }
    }

Upvotes: 1

Views: 913

Answers (1)

Gustavo
Gustavo

Reputation: 685

I think there is a bug in WebView.Source for iOS, the question mark is coming encoded and the system didn't recognize the URL. You can create a custom WebViewRender and replace %3F to ?

On iOS project create a CustomWebViewRender

[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]

namespace Test.iOS.Renders
{
    public class CustomWebViewRenderer : WkWebViewRenderer
    {

        public override WKNavigation LoadRequest (NSUrlRequest request)
        {
            var url = request.Url.ToString().Replace("html%3F", "html?");
            var dotnetURI = new System.Uri(url);

            var idn = new System.Globalization.IdnMapping();
            NSUrl nsURL = new NSUrl(dotnetURI.Scheme, idn.GetAscii(dotnetURI.DnsSafeHost), dotnetURI.PathAndQuery);
               
            return base.LoadRequest(new NSUrlRequest(nsURL));
        }
    }
}

On Xamarin project use your custom WebView

cs file:

namespace Test.Renders
{
    public class CustomWebView : WebView
    {
    }
}

Xaml file:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:test="clr-namespace:Test.Renders"
         ...>
<ContentPage.Content>
    <StackLayout>
        <test:CustomWebView x:Name="map"
                           HorizontalOptions="FillAndExpand"
                           VerticalOptions="FillAndExpand"/>
  ...

Upvotes: 1

Related Questions