Reputation: 21
I am using Capacitor to build an Android app from my Angular web app and I would like to connect the native back button press event with the window.history.back()
such that it does not close the app and instead go back in the window history.
So I added a listener on the backButton event, but it does not get triggered at all, the app just closes immediately.
This is my code for registering the listener:
import { App } from '@capacitor/app';
export function registerAndroidBackSwipe() {
App.addListener('backButton', (event) => {
console.warn(event); // <-- does not even log!
if (event.canGoBack) {
window.history.back();
} else {
App.exitApp().catch(e => console.error(e));
}
});
return true;
}
and I wrap it in a provider function for my standalone Angular app like this:
export function provideAndroidBackSwipe() {
return makeEnvironmentProviders([
{
provide: APP_INITIALIZER,
multi: true,
useFactory: () => {
return Capacitor.getPlatform() === 'android'
? registerAndroidBackSwipe
: () => false;
},
},
]);
}
MainActivity:
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {}
I did a build of the Angular web app, then npx cap sync
, opened Android Studio, did Sync Project with Gradle Files
, but this does not help. I tried all solutions I found online but I could not resolve it with the provided solutions on Stackoverflow and other forums.
I debugged it and the registerAndroidBackSwipe function gets invoked, but the callback in the listener is not called at all, probably because the default behavior is not overwritten somehow, such that the app closes before the callback would be invoked.
Note, that I am not using Ionic - only Capacitor and Angular.
Upvotes: 2
Views: 778
Reputation: 86
EDITED COMPLETELY:
In your call to register the App initializer add deps: ['Capacitor']
before your useFactory
, imported services or usually not allowed in dependencies of APP_INITIALIZER, thats' may be why your listener was not registered and console was not printed.
sorry for the previous answer and not replying earlier.. hope this helps
Upvotes: 0