I’m working on a mobile web app and need to detect when users perform the back swipe gesture on their phones. The tricky part is that I want to execute my own custom function when this happens, but I don’t want to block the normal browser behavior that takes users to the previous page.
Basically, I want both things to happen at the same time - my code should run AND the user should still navigate back like they expect. Is there a way to listen for this swipe back motion in JavaScript while keeping the default navigation working?
I’ve tried some touch event listeners but they seem to interfere with the normal back navigation. What’s the best approach for this?
Here’s another way - use the History API to catch navigation changes. Listen for the popstate
event that fires when users swipe back or use browser history. Set up a custom state when the page loads, then catch popstate to run your function. Don’t call preventDefault()
or history.pushState()
in the handler - just run your code and let the browser handle navigation. This beats touch detection since it works across devices without messing with native gestures. Just keep your code lightweight since popstate fires after navigation starts.
you could also hook into beforeunload
or pagehide
events instead of touch detection. these fire when the swipe back actually triggers navigation, so your code runs without messing with the gesture. pagehide
works better on mobile since it catches all navigation types, including back swipes. just keep your logic quick - there’s limited time before the page disappears.
Had this exact problem last year. Use passive event listeners - they don’t mess with browser navigation. Add { passive: true }
to your touchstart and touchmove listeners. This tells the browser you won’t call preventDefault, so it handles the back gesture normally while still firing your events. I tracked touch coordinates to catch leftward swipes from the screen edge, then fired analytics before the page unloaded. Works great on iOS Safari and Chrome mobile without breaking the back gesture.