WebView AlertDialog is not getting closed in Xamarin Forms

Viewed 28

I was using HybridWebviewRenderer for loading a url on WebView for my application using Xamarin forms. Currently when I click a button in web view, it shows a alert popup with one closeButton. when I click on the closeButton , I'm currently navigating to a page and the navigation is working properly, but when I come back to the same screen, the alert Is not dismissed.? The alert is all done on the web view side , not code is done for creating alert in Xamarin forms. how can we dismiss the alert in web view for Xamarin forms??

1 Answers

I have checked your code, you need to put the if (Control == null) inside the if (e.NewElement != null).You can check the code snippet below for your reference:

using System;
using System.ComponentModel;
using Android.Content;
using Android.Service.Controls;
using Android.Webkit;
using HybridWebView.Droid.Renderer;
using HybridWebView.Renderer;
using Java.Interop;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(CustomWebView), typeof(HybridWebViewRenderer))]
namespace HybridWebView.Droid.Renderer
{
    public class HybridWebViewRenderer : ViewRenderer<CustomWebView, Android.Webkit.WebView>
    {
        const string JavascriptFunction = "function invokeCSharpAction(data){jsBridge.invokeAction(data);}";
        Context _context;
        public string BaseUrl = "file:///android_asset/";
        public HybridWebViewRenderer(Context context) : base(context)
        {
            _context = context;
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
 
            if (e.PropertyName == "Source")
            {
                Control.LoadDataWithBaseURL(BaseUrl, Element.Source, "text/html", "UTF-8", null);
            }
        }

        protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
        {
            base.OnElementChanged(e);
 
            if (e.OldElement != null)
            {
                Control.RemoveJavascriptInterface("jsBridge");
                var hybridWebView = e.OldElement as CustomWebView;
                hybridWebView.Cleanup();
            }
            if (e.NewElement != null)
            {
                if (Control == null)
                {
                    var webView = new Android.Webkit.WebView(_context);
                    webView.Settings.JavaScriptEnabled = true;
                    webView.SetWebViewClient(new JavascriptWebViewClient($"javascript: {JavascriptFunction}"));
                    SetNativeControl(webView);
                }
                Control.AddJavascriptInterface(new JSBridge(this), "jsBridge");
                Control.LoadDataWithBaseURL(BaseUrl, Element.Source, "text/html", "UTF-8", null);
            }
        }
    }
 
Related