Hello,
Welcome to our Microsoft Q&A platform!
You need to create a custom renderer for webview in Xamarin Android.
Then make sure WebView has enabled javascript and the WebViewClient is set correctly.
web.Settings.JavaScriptEnabled = true;
web.SetWebViewClient(new WebviewClient());
Then set a SetDownloadListener for Android.Webkit.WebView
, Then use DownloadManager to download the file. Due to the Android 11 storage limitation. I store download file to the application's top-level directory with Xamarin.Essentials: File System Helpers.
[assembly: ExportRenderer(typeof(Xamarin.Forms.WebView), typeof(MyWebviewCustomRenderer))]
namespace App11.Droid
{
internal class MyWebviewCustomRenderer : WebViewRenderer
{
public MyWebviewCustomRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
var webView = new global::Android.Webkit.WebView(Android.App.Application.Context);
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new WebViewClient());
webView.SetWebChromeClient(new WebChromeClient());
webView.SetDownloadListener(new CustomDownloadListener());
this.SetNativeControl(webView);
var source = e.NewElement.Source as UrlWebViewSource;
if (source != null)
{
webView.LoadUrl(source.Url);
}
}
}
public class CustomDownloadListener : Java.Lang.Object, IDownloadListener
{
public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
{
try
{
DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(url));
request.AllowScanningByMediaScanner();
request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
// if this path is not create, we can create it.
string thmblibrary = FileSystem.AppDataDirectory + "/download";
if (!Directory.Exists(thmblibrary))
Directory.CreateDirectory(thmblibrary);
request.SetDestinationInExternalFilesDir(Android.App.Application.Context, FileSystem.AppDataDirectory, "download");
DownloadManager dm = (DownloadManager)Android.App.Application.Context.GetSystemService(Android.App.Application.DownloadService);
dm.Enqueue(request);
}
catch (Exception)
{
throw;
}
}
}
}
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.