HTMLtoApphtmltoapp.net Build free
free utility · runs in your browser

Android back button snippet

In an HTML app, Android's back button goes back in the page's history. This snippet adds a history entry whenever a modal or menu opens, so back closes it — exactly what Android users expect.

How back works in an HTML app

When the user presses back, the app asks the WebView to go back one history entry; when there is no entry left, the app closes. Navigating between pages or hash routes creates entries automatically. Opening a modal does not — so back skips the modal and leaves the screen, which feels broken. Pushing a history entry when the modal opens fixes that: back pops the entry, the popstate handler closes the modal, and the user stays where they were.

Rules for a natural back button

  • Back closes the topmost overlay first: modals, drawers, menus, image viewers, search panels.
  • Back walks back through screens; it exits only from the first screen.
  • Use history.replaceState only for redirects (after login), never for normal navigation.
  • Do not trap the user: never push entries in a loop to prevent leaving.

Routing for frameworks: SPA routing inside an APK.

Questions people ask

Why does the back button close my HTML app instead of my popup?

Opening a popup does not create a history entry, so back goes to the previous page — or exits. Push a history entry when the popup opens and close it on popstate.

Do I need native code to handle the back button?

No. The app maps Android's back button to WebView history, so the History API is all you need.

Your HTML is one upload away from an app

Install the free builder, drop in your HTML file or ZIP, and download a signed APK in a few minutes. No watermark, no card, no Android Studio.

Build my APK free