I'm developing an app with Angular 7 and Cordova 8. I want to override the cordova back button event, to prevent the app from closing by adding an event listener as described in the cordova docs
My code looks like this:
let onDeviceReady = () => {
enter code hereconsole.log("Bootstraping Module...")
document.addEventListener("backbutton", (e) => {e.preventDefault(); e.stopPropagation(); console.log("backbutton"); return false;}, false);
platformBrowserDynamic().bootstrapModule(AppModule);
};
document.addEventListener('deviceready', onDeviceReady, false);
According to the docs this should prevent the app from closing. I know that the preventDefault
, stopPropagation
and return false
calls are not necessary, but I found the as possible solutions to my problem, which all didn't work.
When I press the back button, I see the backbutton
print, however, the app is still closing.
Tested on Android.
Update: After debugging the issue using logcat I could see the message WARNING: Back Button Default Behavior will be overridden. The backbutton event will be fired!
which is logged in the CoreAndroid plugin class when the back button is overriden in the native Android app. Still when I press the button, the app exits
Update: The issue was related to OnsenUI, see my answer below
I managed to solve the issue. It wasn't caused by Cordova or Angular, but by OnsenUI, which I used for input components. By default it overwrites all cordova handlers for the backbutton, as it provides its own functionality. You can read more here