Blocking Navigation Gestures On iOS Safari

iOS Safari 13.4+ allows us to block back and forward navigation gestures. Super useful for media galleries and image croppers where users interact with elements on the side of the viewport and most likely don’t want to navigate to another page. Let’s take a minute and look at the code snippet.

The only thing we need to do is prevent the default action of the "touchstart" event. We can do this with the preventDefault() method.

<div style="height:100px">Our element that prevents navigation</div>

<script>
    const element = document.querySelector('div');

    element.addEventListener('touchstart', (e) => {
        // prevent swipe to navigate gesture
        e.preventDefault();
    });
</script>

Open this article on iOS 13.4+ and try it out with the element below.

This element prevents navigation, swipe from left to right from the edge of the screen, nothing will happen.

A demo on iOS

We do need to check if the "touchstart" event originated near the edge of the viewport, if we don’t the user won’t be able to scroll the view, we can do this by checking if pageX is below or above a certain value.

<div style="height:100px">Our element that prevents navigation</div>

<script>
    const element = document.querySelector('div');

    element.addEventListener('touchstart', (e) => {
        // is not near edge of view, exit
        if (e.pageX > 20 && e.pageX < window.innerWidth - 20) return;

        // prevent swipe to navigate back gesture
        e.preventDefault();
    });
</script>

That’s it!

We can now prevent users from accidentally navigating to another page. With great power comes great responsibility. We don’t want to frustrate users, so only use this where it makes sense, for example in a full width swipeable image gallery or when users interact with controls near the edge of the screen.

I share web dev tips on Twitter, if you found this interesting and want to learn more, follow me there

Or join my newsletter

More articles More articles