Hardware Back Button
The hardware back button is found on most Android devices. In native applications it can be used to close modals, navigate to the previous view, exit an app, and more. By default in Ionic, when the back button is pressed, the current view will be popped off the navigation stack, and the previous view will be displayed. If no previous view exists in the navigation stack, nothing will happen. This guide will show how to customize the behavior of the hardware back button.
The hardware back button refers to the physical back button on an Android device and should not be confused with either the browser back button or ion-back-button. The information in this guide only applies to Android devices.
Overview
Ionic Framework emits an ionBackButton event when a user presses the hardware back button in supported environments.
When listening for the ionBackButton event, you can register a handler to be fired. This handler can perform actions such as quitting the app or opening a confirmation dialog. Each handler must be assigned a priority. By default, only one handler is fired per hardware back button press. The priority value is used to determine which callback should be called. This is useful because if you have a modal open, you likely would not want the modal to close and the app to navigate backwards when pressing the hardware back button. Only running one handler at a time allows the modal to close but still requires another press of the hardware back button to navigate backwards.
There are situations where you might want to have multiple handlers fired. Each handler callback passes in a function as a parameter that can be used to tell Ionic to call the next handler.
Support
The table below shows how hardware back button support varies by environment.
| Environment | Status |
|---|---|
| Capacitor | Supported only when the @capacitor/app package is installed. |
| Cordova | Supported |
| Browser | Supported only when experimentalCloseWatcher is true and the platform supports the Close Watcher API. |
| PWA | Supported only when experimentalCloseWatcher is true and the platform supports the Close Watcher API. |