xamarin.forms Handle Clicked event on WebView

后端 未结 5 2288
陌清茗
陌清茗 2020-12-06 12:39

I want to handle the click/tap event on a WebView control

I\'ve tried the GestureRecognizers but nothing happens, i think maybe the WebView has some sort of making t

5条回答
  •  悲&欢浪女
    2020-12-06 12:54

    You can use the HybridWebView from XLabs, and use javascript injection to invoke and handle clicks in your Xamarin control. The injected javascript code can add a click-event listener at capture stage. When a click is detected it uses Native callback to send information back to C# code.

    For example - you can define a custom control like this:

    public class ClickEventArgs : EventArgs
    {
        public string Element { get; set; }
    }
    
    public class ClickableWebView : XLabs.Forms.Controls.HybridWebView
    {
        public event EventHandler Clicked;
    
        public static readonly BindableProperty ClickCommandProperty =
            BindableProperty.Create("ClickCommand", typeof(ICommand), typeof(ClickableWebView), null);
    
        public ICommand ClickCommand
        {
            get { return (ICommand)GetValue(ClickCommandProperty); }
            set { SetValue(ClickCommandProperty, value); }
        }
    
        public ClickableWebView()
        {
            LoadFinished += (sender, e) => 
                InjectJavaScript(@"
                document.body.addEventListener('click', function(e) {
                    e = e || window.event;
                    var target = e.target || e.srcElement;
                    Native('invokeClick', 'tag='+target.tagName+' id='+target.id+' name='+target.name);
                }, true /* to ensure we capture it first*/);
            ");
    
            this.RegisterCallback("invokeClick", (string el) => {
                var args = new ClickEventArgs { Element = el };
    
                Clicked?.Invoke(this, args); 
                ClickCommand?.Execute(args);
            });
        }
    }
    

    Sample XAML usage

    
    

    and sample code-behind

    void Handle_Clicked(object sender, CustomWebView.ClickEventArgs e)
    {
        Xamarin.Forms.Application.Current.MainPage.DisplayAlert("WebView Clicked", e.Element, "Dismiss");
    }
    

    ** Output **

    Alternatively, you can also bind ClickCommand property to implement this using MVVM pattern.

提交回复
热议问题