Ionic 4 | Overridden Back Press Event and Show Exit Confirm on Application Close

We have already discussed How to Override Back Press Event in Ionic’s V3 which we can easily do by using Platform’s registerBackButtonAction method. But in Ionic’s V4 version this method simply does not work.

So in this post, we will create an Ionic V4 Application to demonstrate overriding of Back Press Event in Ionic 4 Application. We will also discuss how to get the current Component name to handle it more conveniently.

Let’s create an Ionic 4 Application first using following CLI command as Ionic 4 is still in beta phase.

$ ionic start Ionic4BackPress blank --type=angular

In Ionic 4 Application we use Platform's backButton Interface as follows

    this.platform.backButton.subscribeWithPriority(999990,  () => {
        //alert("back pressed");

Here 999990 is the priority, we need to give this number due to some ongoing bugs in library 😛

Implement Back Press Event in any specific Component

Open file then replace the following code

import { Component } from '@angular/core';
import { Platform } from '@ionic/angular';

  selector: 'app-home',
  templateUrl: '',
  styleUrls: [''],
export class HomePage {

  // This property will save the callback which we can unsubscribe when we leave this view
  public unsubscribeBackEvent: any;

    private platform: Platform
  ) { }

  //Called when view is loaded as ionViewDidLoad() removed from Ionic v4

  //Called when view is left
  ionViewWillLeave() {
    // Unregister the custom back button action for this page
    this.unsubscribeBackEvent && this.unsubscribeBackEvent();

  initializeBackButtonCustomHandler(): void {
    this.unsubscribeBackEvent = this.platform.backButton.subscribeWithPriority(999999,  () => {
        alert("back pressed home" +;
    /* here priority 101 will be greater then 100 
    if we have registerBackButtonAction in app.component.ts */


Here priority is 999999 which should be greater then app.component.ts event priority.

In ionViewWillLeave event will unsubscribe BackButton event when app moves to any other view/ page.


0 0 vote
Article Rating
Notify of
Oldest Most Voted
Inline Feedbacks
View all comments
6 months ago

I used this code but when I put in ionViewWillLeave I get an error message saying this.unsubscribeBackEvent is not a function. Please let me know what it is that I am doing wrong. Everything else is working just as I would like it except this function.

code android example
1 year ago

i think code this add event when click