In an HTML app, Android's back button (or back gesture) goes back one step in the WebView's history — the previous page or hash — and closes the app when there is no history left. Dialogs, menus and tabs that do not create history entries are skipped, so push a history entry when you open them and close them on popstate.
The pattern
function openLayer(el) {
el.hidden = false;
history.pushState({ layer: el.id }, '');
}
addEventListener('popstate', () => {
document.querySelectorAll('.layer:not([hidden])').forEach(el => el.hidden = true);
});
// closing with an on-screen ✕ button: go back so history stays in sync
function closeLayer() { if (history.state && history.state.layer) history.back(); }Single-page apps
Hash routing (#/settings) and the History API both create entries, so back walks through your screens. Inside an APK, prefer hash routing: history-mode URLs like /settings do not exist as files and break on reload.
Exiting
On the first screen, back closes the app — what Android users expect. Avoid trapping users with endless pushState calls.
Frequently asked questions
Can I disable the back button in my HTML app?
You should not trap users. You can make back close in-app layers first, as above; on the first screen it should exit.