I am trying to prevent swipe back/forward navigation in my Web App if I am on a certain page in app (e.g., a document in edit and I have a resize handle for an object which is on the edge of the screen – I want to block page navigation if the event is over the canvas I am drawing).
Started from https://medium.com/@joelmalone/prevent-edge-swipe-gestures-in-your-html-game-but-only-in-safari-fba815a529a2:
/**
* Prevents the mobile browser behaviour that moves to the next or previous page
* in your browser's history when you swipe in from the edge of the screen.
*
* Only seems to work reliably on Safari. Testing on Chrome iOS showed
* inconsistent effectiveness. Did not test other browsers.
*
* @returns A function to call to resume the browser's normal behaviour.
*/
function preventBrowserHistorySwipeGestures() {
function touchStart(ev) {
if (ev.touches.length === 1) {
const touch = ev.touches[0];
if (
touch.clientX < window.innerWidth * 0.1 ||
touch.clientX > window.innerWidth * 0.9
) {
ev.preventDefault();
}
}
}
// Safari defaults to passive: true for the touchstart event, so we need to explicitly specify false
// See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
const options= { passive: false };
window.addEventListener("touchstart", touchStart, options);
return () => window.removeEventListener("touchstart", touchStart, options);
}
This code works perfectly fine for iOS Safari + Chrome (gesture enabled by default on iOS). But I couldn’t make it work for Chrome Android (on Android I enable the gesture via Settings -> Display -> Navigation Bar -> Swipe).
Found event.preventDefault() not working for android chrome, but doesn’t help me. I literally want to block this event.