androidwebviewmaui

MAUI Android webview proxy


how to connect a proxy with webview for android (MAUI)?

for windows it's simple because you can use the CoreWebView2EnvironmentOptions class, unfortunately for andorid there is no such possibility. Could anybody help me to set proxy?

on windows version I use:

CoreWebView2EnvironmentOptions Options = new CoreWebView2EnvironmentOptions();
Options.AdditionalBrowserArguments = "--proxy-server=host:port";
CoreWebView2Environment env =
    await CoreWebView2Environment.CreateAsync(null, null, Options);

webView.EnsureCoreWebView2Async(env);

but options does not exist in ANDROID
I need to set host:port proxy


Solution

  • You can try to use the Xamarin.AndroidX.WebKit nuget package for the android. In addition, for the windows, there is no CoreWebView2Environment.CreateAsync(null, null, Options); method. The full code:

    #if WINDOWS
                var webview2 = webview.Handler.PlatformView as Microsoft.UI.Xaml.Controls.WebView2;
                Microsoft.Web.WebView2.Core.CoreWebView2EnvironmentOptions Options = new Microsoft.Web.WebView2.Core.CoreWebView2EnvironmentOptions();
                Options.AdditionalBrowserArguments = "--proxy-server";
                Microsoft.Web.WebView2.Core.CoreWebView2Environment env = await Microsoft.Web.WebView2.Core.CoreWebView2Environment.CreateWithOptionsAsync(null, null, Options);
                await webview2.EnsureCoreWebView2Async(env);
                webview.Source = "the url";
    #elif ANDROID
                if (AndroidX.WebKit.WebViewFeature.IsFeatureSupported(AndroidX.WebKit.WebViewFeature.ProxyOverride))
                {
                    var proxyurl = "host:port";
                    var proxyconfig = new AndroidX.WebKit.ProxyConfig.Builder().AddProxyRule(proxyurl).AddDirect().Build();
                    AndroidX.WebKit.ProxyController.Instance.SetProxyOverride(proxyconfig, new MyExcuter(), new MyRunable());
                }
                webview.Source = "the url";
    #endif
    

    And in the xaml, there is <WebView x:Name="webview" .../>.You can put the code above in the Page's override OnHandlerChanged method.

    #if ANDROID
        public class MyExcuter : Java.Lang.Object, Java.Util.Concurrent.IExecutor
        {
            public void Execute(Java.Lang.IRunnable? command)
            {
               
            }
        }
        public class MyRunable : Java.Lang.Object, Java.Lang.IRunnable
        {
            public void Run()
            {
               
            }
        }
    #endif