17

My current setup is:

@capacitor/core: 3.0.0, @ionic-native/core: 5.0.7

I'm trying to change the behavior of my app to not close the app, but go back in the navigation stack. To my knowledge, the hardware back button on Android devices did not automatically close the app until I upgraded Capacitor to 3.0.0

What is confusing me though, is how I have absolutely 0 code for handling the back button functionality, and from everything I'm searching online shows the back button doing nothing by default, not automatically closing the app as the default (as mine seems to be doing). I've searched all the project files for anything to do with "platform", "backButton", and "App.Exit" and was unable to find any code that may be causing the app to close.

I've tried subscribing to the back button press event using the below code and it is never ran. The app closes instead of showing the alert dialog. I've changed the priority from 0, 10, and 99 (all priorities listed in the Ionic documentation)

this.platform.backButton.subscribeWithPriority(10, () => {
  alert('Back button pressed!');
});
kasprdev
  • 651
  • 1
  • 4
  • 14

7 Answers7

29
  1. Install capacitor app.

    npm install @capacitor/app

  2. Import it.

    import { App as CapacitorApp } from '@capacitor/app';

  3. Add back listener if can go back then we can push to back or exit the app.

    CapacitorApp.addListener('backButton', ({canGoBack}) => {
      if(!canGoBack){
        CapacitorApp.exitApp();
      } else {
        window.history.back();
      }
    });
    
Vatsal Dholakiya
  • 545
  • 4
  • 19
Siyahul Haq
  • 329
  • 4
  • 6
  • Thx, fixed the hardware button handling on Android. Still looking for a fix for iOS. – Mario Nov 04 '21 at 11:37
  • This is not working for me. I tried like a million times but the event doesn't get triggered. – Mr Khan Feb 08 '22 at 13:05
  • 2
    @Mr Khan check https://capacitorjs.com/docs/apis/app for extra config you need for the `AndroidManifest.xml` – Ignacio Bustos Feb 27 '22 at 15:23
  • @mario, I am afraid, there is no back button in iOS... I know, I know, I also cannot reach with one single right hand to the top left corner of the screen to go back (except in some apps), but this is the life when Marketing > Usability. – Ignacio Bustos Feb 27 '22 at 15:44
  • @IgnacioBustos boss do you have any update on IOS ? – Space Nov 30 '22 at 18:28
20

So, I feel a bit dumb after realizing this, but it is because I had to run the below commands, because I apparently didn't update them when upgrading Capacitor a while back. Make sure all of your plugins are fully updated, yours may be different than mine.

npm install @capacitor/app
npx cap sync
kasprdev
  • 651
  • 1
  • 4
  • 14
  • Did this solve your issue? I'm having the same issue, I ran these commands but back button still closes my app. :/ – Ani Jun 01 '21 at 07:51
  • I have noticed that back button runs properly in "@capacitor/core": "^2.4.7", but not in version 3.0.0 and I must use the latest version. Do you have any idea about my issue? – Ani Jun 01 '21 at 09:49
  • 1
    Hi I am also facing this issue. Could you perhaps enlighten us more on how to resolve it? What does @capacitor/app plugin do? Thank you in advance. – ZXERSTON Jun 20 '21 at 00:39
  • 1
    @Ani Sorry, just now seeing this. My issue was just because I didn't upgrade ALL my capacitor packages to their latest version. In my specific case, I forgot to upgrade @capacitor/app and something in that package was causing the back button to cause a crash. – kasprdev Jun 29 '21 at 00:29
  • 2
    It's ok, I solved my issue too. I had forgotten to update @capacitor/cli . That's why back button was not working in my case. @ZXERSTON, make sure to update all capacitor packages such as: "@capacitor/android": "^3.0.0", ` "@capacitor/app": "^1.0.0", "@capacitor/core": "^3.0.0", "@capacitor/haptics": "^1.0.0", "@capacitor/keyboard": "^1.0.0", "@capacitor/network": "^1.0.0", "@capacitor/status-bar": "^1.0.0", "@capacitor/cli": "^3.0.0" ` – Ani Jun 29 '21 at 06:19
  • Can you please update your answer with the page link where this is mentioned on the official website? – Ankur Shah Aug 07 '21 at 18:23
  • I am also facing same issue I have updated all plugins still hardware back closing app.Its working properly on dev build . Kindly lete know any one fixed the issue – spsaravananct Aug 22 '21 at 07:59
  • @spsaravananct did you fix your issue I am also having the same problem back button handler is working properly in dev build but in production it is closing the app – silentnow May 08 '22 at 18:29
5

I had the same issue and I tried installing all the plugins like it says here

npm install @capacitor/app @capacitor/haptics @capacitor/keyboard @capacitor/status-bar

After I finished installing, I still got the error. Also my PushNotifications plugin was not working either.

My problem was I forgot to delete the OnCreate method from MainActivity.java. So if you still have the problem after installing the plugins, try to delete OnCreate method so your MainActivity.java looks like this:

 public class MainActivity extends BridgeActivity {}

See more here.

It also fixed my PushNotifications plugin.

If I understand it correctly, if you have any plugin that is not registered correctly, it will cause this kind of error. This answer also helped me.

Callan
  • 1,179
  • 1
  • 7
  • 18
3

https://stackoverflow.com/a/69084017/19086322

This post work really good for me !!

Before this post i made these commands and after it worked:

npm install @capacitor/app                                             
npx cap sync
Cryptoer17
  • 61
  • 5
1

I have the same issue and adding @capacitor/app to my App worked for debugging puposes. The Problem is, when I build a release app, it still closes the app.

--- EDIT ---

I fixed the issue by building a completely new Ionic App (with the latest versions of everything) and then copying my code. I assume it really had something to do with the installed versions of the Ionic and Capacitor packages

Micky
  • 11
  • 3
0

You need to use below code to handle the Hardware back button in Ionic app:

//back button handle
//Registration of push in Android and Windows Phone
let lastTimeBackPress: number = 0;
let timePeriodToExit: number = 2000;

platform.registerBackButtonAction(() => {

    //Double check to exit app
    if (new Date().getTime() - lastTimeBackPress < timePeriodToExit) {
        //this.platform.exitApp(); //Exit from app

        this.appMinimize.minimize().then(() => {
            console.log('minimized successfully');
        });
    } else {

        this.toastCtrl.create({
            message: this.translate.instant('EXIT_APP_MESSAGE'),
            duration: 3000,
            position: 'bottom'
        }).present();

        lastTimeBackPress = new Date().getTime();
    }
});
H_H
  • 1,460
  • 2
  • 15
  • 30
0

for android:

import android.webkit.WebView;
import com.getcapacitor.BridgeActivity;

public class MainActivity extends BridgeActivity {
    //in my case I call it the JS function when I press the back button
    @Override
    public void onBackPressed() {
        WebView webView = getBridge().getWebView();

        webView.loadUrl("javascript:pressBack()");

        // in Index.html create tag
        //<script type="text/javascript">
        //   function  pressBack(){
        //      alert('yes!!')
        //   } 
        //</script>

        return;
    }
}
trickymind
  • 557
  • 5
  • 21
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 28 '22 at 07:38