Home > other >  Xamarin.macOS Navigated event not fire for CustomWebView
Xamarin.macOS Navigated event not fire for CustomWebView

Time:11-19

I have created custom renderer for my WebView because I need to set property CustomUserAgent. But for my CustomWebView event Navigated is not fired. As I understand I need set NavigationDelegate but can't find any working example. Here is my code:

[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace DesktopClient.MacOS.CustomRenderers
{
    public class CustomWebViewRenderer : ViewRenderer<CustomWebView, WKWebView>
    {
        private WKWebView wkWebView;

        protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
        {
            base.OnElementChanged(e);            

            if (this.Control == null)
            {
                WKWebViewConfiguration config = new();                

                this.wkWebView = new WKWebView(this.Frame, config)
                {
                    NavigationDelegate = new WKNavigationDelegate()
                };

                this.SetNativeControl(this.wkWebView);

                WKWebViewContainer.WKWebView = this.wkWebView;
            }

            if (e.NewElement != null)
            {
                UrlWebViewSource source = (UrlWebViewSource)e.NewElement.Source;

                if (source != null)
                {
                    this.Control.LoadRequest(new NSUrlRequest(new NSUrl(source.Url)));
                }
                
                this.Control.CustomUserAgent = e.NewElement.UserAgent;
                this.wkWebView.NavigationDelegate = new WKNavigationDelegate();
            }
        }
    }
}

CodePudding user response:

Create a new class inherit from WKNavigationDelegate and assign to Webview.NavigationDelegate ,and then you can override the method like DidFinishNavigation in the new class .

Sample code

NavigationDelegate = new MyDelegate();

public class MyDelegate : WKNavigationDelegate {

    public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
    {
            
    }
}

However , I found the method DidFinishNavigation does not trigger at initial load ,it can only be triggered when we navigate to other web page.

  • Related