Ionic: How to Simulate Android back button in Browser
When we are developing and testing our Ionic apps is common that we use the browser for it, because we have advantages like hot reloading, dev tools for debugging, and so on. Because of this, we have some trouble when trying to simulate behavior that only happens on real devices.
One of these behaviors is the Android Back button. In some cases, we want to do a specific action when the back button is tapped. Most commonly we want to intercept the default behavior and, for example, show a dialog asking if the user wants to go back.
Here is the big trouble we are in. This behavior only can be tested on real devices, so we will need to build (generate APK/AAB) our application again and again to test the behavior. It’s so boring.
Today I have an amazing tip to prevent this boring and improve your productivity when trying to simulate the back button behavior. Today we’ll learn how to simulate the Android back button in the browser.
Step 0— Have an application
For this experiment, we can create a really simple application that contains two pages. The first page is the home containing a button that opens the second page, and the second page contains some business logic applied to the back button, using Platform.
The general idea is to test the behavior of Android back button on the second page.
We can start creating our app by running the following command.
ionic start android-backbutton blank --type=ionic-angular
After project creation, go to the project folder and create a new page by running:
ionic g page second
Our project structure is like the one shown below.
On home.page.html
we have only an ion-button
with a routerLink
to /second
and on second.page.html
we have a Lorem ipsum… text.
The most important code here is the one of second.page.ts
.
import { Location } from '@angular/common';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { AlertController, Platform } from '@ionic/angular';
import { Subscription } from 'rxjs';@Component({
selector: 'app-second',
templateUrl: './second.page.html',
styleUrls: ['./second.page.scss'],
})export class SecondPage implements OnInit, OnDestroy {
subscription: Subscription; constructor(
private alertCtrl: AlertController,
private platform: Platform,
private location: Location
) { } ngOnDestroy() {
delete (window as any).simulateBackButton;
this.subscription.unsubscribe();
} ngOnInit() {
this.subscription = this.platform.backButton.subscribe(async (value) => {
console.log('backbutton!');
const dialog = await this.alertCtrl.create({
header: 'Confirmation',
message: 'Are you sure you want to exit?',
buttons: [
{
text: 'YES',
handler: () => {
console.log('pop this page');
this.location.back();
}
},
{
text: 'NO',
role: 'cancel'
}
]
});
dialog.present();
}); // let event = new Event('ionBackButton'); // it works but an exception is raised let event = new CustomEvent('ionBackButton', {
detail: {
register: (priority, handler) => {
console.log({priority, handler});
}
}
}); (window as any).simulateBackButton = () => {
document.dispatchEvent(event);
};
} back() {
(window as any).simulateBackButton();
}
}
The complete application can be found at https://github.com/geeksilva97/Medium/tree/master/android-backbutton.
Step 1 — How does Ionic Framework handle back button action?
From the documentation we have:
The
ionBackButton
event will not be emitted when running an app in a browser or as a PWA.
Also from the documentation we have:
When running in a Capacitor or Cordova application, Ionic Framework will emit an
ionBackButton
event when a user presses the hardware back button.
The first information we already know even before the introduction of this post (by self-experience), the second is information that maybe you didn’t know until now, and is this information that we will use to solve our problem.
NOTE: When triggering this event, the behavior will be the same as the Back button. Therefore, all attached actions will be performed..
Step 2 — Creating a custom event to trigger the back button action
We already know what to do, right? We need to create an event called ionBackButton
and dispatch it manually. It seems very complex at first, It looks very complex at first, but it’s actually quite simple.
We basically need two things. The event and a target to dispatch this event.
Create events is simple, for this we can use the Event constructor of JavaScript as shown below.
const myEvent = new Event(‘awesome’);
To dispatch the event we need an EventTarget. EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them.
Objects like Element, Window, and Document are the most common event targets. For our necessity, we can use Document as the EventTarget and dispatch event as shown below
document.dispatchEvent(new Event(‘awesome’));
Finally to simulate the back button let’s dispatch the ionBackButton event.
document.dispatchEvent(new Event(‘ionBackButton’));
Step 3 — Testing the behavior
To test the behavior let us run our app in the browser, open the JavaScript console, and put the code to dispatch the ionBackButton event.
Is possible to see the desired behavior happening. When we fire the event, a confirmation dialog is opened.
As you can see although it working an exception is raised. In my experiments is only happens for the first time. But if you want to avoid this exception you can use CustomEvent as shown below.
let event = new CustomEvent('ionBackButton', {
detail: {
register: (priority, handler) => {
console.log({priority, handler});
}
}
});// running
document.dispatchEvent( event );
The code above also defines an Event, but for this event, we can put data in detail property. It works like a mock of the event.
It’s still boring. We can make it more testable by putting this code inside of our component.
Now we don’t need to copy the dispatch
at console, we only need to click the button.
Remember to remove this button after testing.
Summary
In this post, we saw a way to simulate the hardware back button which is an amazing tip that will improve your productivity when developing this kind of feature.
Also, you saw some concepts about Events which can be useful in many situations.
If you liked this content, please consider clapping this post 👏🏽 and share it with your friends.
That’s all. See ya!
References
- https://ionicframework.com/docs/api/back-button
- https://ionicframework.com/docs/developing/hardware-back-button#hardware-back-button-in-capacitor-and-cordova
- https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events
- https://github.com/geeksilva97/Medium/tree/master/android-backbutton.