Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xamarin.forms Handle Clicked event on WebView

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 the event handled "true".

<WebView>
   <WebView.GestureRecognizers>
      <TapGestureRecognizer
              Tapped="OnWebViewClick"
              NumberOfTapsRequired="1" />
   </WebView.GestureRecognizers>
</WebView>

And I've tried it using c# code behind too but no luck :/

like image 228
Esam Sherif Avatar asked May 22 '15 12:05

Esam Sherif


2 Answers

I am using this hack: put the WebView in a Grid and insert a BoxView in the same cell. Then put a handler on the BoxView.

like image 89
Charles Roddie Avatar answered Sep 19 '22 13:09

Charles Roddie


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<ClickEventArgs> 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

<local:ClickableWebView 
    Uri="https://google.com" 
    Clicked="Handle_Clicked"
/>

and sample code-behind

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

** Output **

sample output

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

like image 39
Sharada Gururaj Avatar answered Sep 19 '22 13:09

Sharada Gururaj