How can I implement right and left swipe gestures to navigate back and forward in a .NET MAUI WebView? My current implementation isn't working, and the WebView's navigation stack seems to always return null. Can you help me troubleshoot and improve this

Satyasai Gunnam 20 Reputation points
2024-11-25T10:18:23.1733333+00:00
 public WebAppView()

 {

     InitializeComponent();

     BindingContext = this;

     _globalData = ServiceHelper.GetService<GlobalDataService>();

     _Notification = ServiceHelper.GetService<NotificationService>();

    // _loadingStopwatch = new Stopwatch();

     //StartFloatingAnimation();

     #region Bind WebView Events

     webView.Loaded += OnWebViewLoaded;

     webView.Navigating += OnWebViewNavigating;

     webView.Navigated += OnWebViewNavigated;

     if(_globalData.IsUserSaas)

     {

         webView.Source = $"{Constants.BaseUrl}admin/dashboard";

     }

     else

     {

         webView.Source = _latestUrl;

     }

     **AddGestureRecognizers();**

     #endregion

 }

 #region WebView Events

 private void AddGestureRecognizers()

 {

     // Add a swipe gesture recognizer for going back in history

     var swipeRightGestureRecognizer = new SwipeGestureRecognizer { Direction = SwipeDirection.Right };

     swipeRightGestureRecognizer.Swiped += OnSwipeRight;

     webView.GestureRecognizers.Add(swipeRightGestureRecognizer);

     // Add a swipe gesture recognizer for going forward in history

     var swipeLeftGestureRecognizer = new SwipeGestureRecognizer { Direction = SwipeDirection.Left };

     swipeLeftGestureRecognizer.Swiped += OnSwipeLeft;

     webView.GestureRecognizers.Add(swipeLeftGestureRecognizer);

 }

 private void OnSwipeRight(object sender, SwipedEventArgs e)

 {

     // Go back if possible

     if (webView.CanGoBack)

     {

         webView.GoBack();

     }

 }

 private void OnSwipeLeft(object sender, SwipedEventArgs e)

 {

     // Go forward if possible

     if (webView.CanGoForward)

     {

         webView.GoForward();

     }

 }
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,684 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 44,946 Reputation points Microsoft Vendor
    2024-11-27T07:02:48.9266667+00:00

    Hello,

    You need to rewrite the TouchListener of WebView so that WebView can respond to left and right swipe gestures. Please refer to the following code.

    Step 1. Create custom TouchListener and native GestureDetector in Platform/Android folder.

    
    namespace MauiApp15.Platforms.Droid
    
    {
    
        public class OnSwipeTouchListener : Java.Lang.Object, IOnTouchListener
    
        {
    
     
    
            private GestureDetector gestureDetector;
    
            private Android.Webkit.WebView webView;
    
     
    
            public OnSwipeTouchListener(Android.Webkit.WebView webView)
    
            {
    
                this.webView = webView;
    
                gestureDetector = new GestureDetector(Platform.CurrentActivity,new GestureListener(webView));
    
            }
    
            public bool OnTouch(global::Android.Views.View? v, MotionEvent? e)
    
            {
    
                return gestureDetector.OnTouchEvent(e);
    
            }
    
        }
    
        public class GestureListener :Java.Lang.Object, GestureDetector.IOnGestureListener
    
        {
    
            private Android.Webkit.WebView webView;
    
            public GestureListener(Android.Webkit.WebView webView)
    
            {
    
                this.webView = webView;
    
            }
    
     
    
            public bool OnDown(MotionEvent e)
    
            {
    
                return false;
    
            }
    
     
    
            public void OnLongPress(MotionEvent e)
    
            { 
    
            }
    
     
    
            public bool OnScroll(MotionEvent? e1, MotionEvent e2, float distanceX, float distanceY)
    
            {
    
                return false ;
    
            }
    
     
    
            public void OnShowPress(MotionEvent e)
    
            {
    
            }
    
     
    
            public bool OnSingleTapUp(MotionEvent e)
    
            {
    
                return false;
    
            }
    
     
    
            public bool OnFling(MotionEvent? e1, MotionEvent e2, float velocityX, float velocityY)
    
            {
    
                float x = e2.GetX() - e1.GetX();
    
                float y = e2.GetY() - e1.GetY();
    
                judgeSwiperDirection(x, y);
    
                return true;
    
            }
    
            private void judgeSwiperDirection(float xAxis, float yAxis)
    
            {
    
     
    
                bool isYInControlled = Math.Abs(yAxis) <= 100;
    
     
    
                if (isYInControlled)
    
                {
    
                    if (xAxis > 25)
    
                    {
    
                        if (null != webView && webView.CanGoForward())
    
                        {
    
                            webView.GoForward();
    
                        }
    
                    }
    
                    else if (xAxis < -25)
    
                    {
    
                        if (null != webView && webView.CanGoBack())
    
                        {
    
                            webView.GoBack();
    
                        }
    
                    }
    
                }
    
            }
    
        }
    
     
    
    }
    
    

    Step 2. Set up bindings for the WebView in your Maui page.

    
         protected override void OnHandlerChanged()
    
            {
    
                base.OnHandlerChanged();
    
    #if ANDROID
    
                var w = webview.Handler.PlatformView as Android.Webkit.WebView;
    
                if (w != null)
    
                {
    
                    OnSwipeTouchListener onSwipeTouchListener = new OnSwipeTouchListener(w);
    
                    w.SetOnTouchListener(onSwipeTouchListener);
    
                }
    
    #endif
    
            }
    
    

    Best Regards,

    Alec Liu.


    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.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.