Reputation: 617
I've followed the example code in the Cordova docs to override the device back button (using ES6), but it doesn't work as expected:
const onBackButtonPress = () => {
console.log('pressed');
};
document.addEventListener('backbutton', onBackButtonPress, false);
When I run the app on my Android device, my override code gets invoked, but the app also exits as if the default back button action is also being invoked.
How can I prevent the app from exiting when the back button is pressed?
I've already tried adding e.preventDefault()
to the callback function for addEventListener
I'm doing this after the deviceready
event has fired.
I'm using Cordova 7.0.1 and my platform is cordova-android 6.2.3
Upvotes: 2
Views: 3342
Reputation: 1
For those of you that are using React, you may want to override the back button behaviour inside a component. If you have a changing function to navigate back, it can be a bit challenging, since React rerenderings can produce undesired consequences.
This is the code I use for this situation:
function MyComponent(): JSX.Element {
// ...
useEffect(() => {
const handleDeviceBackButton = (event: Event) => {
event.preventDefault();
navigateBack();
};
document.addEventListener("backbutton", handleDeviceBackButton);
return () => {
document.removeEventListener("backbutton", handleDeviceBackButton);
};
}, [navigateBack]);
// ...
}
React documentation says:
Your setup function may also optionally return a cleanup function.
If we use the cleanup function to remove the listener, we avoid undesired repetitions.
Upvotes: 0
Reputation: 65
While all answers here are correct, on some devices they still don't work. I had the same issue on Huawei P smart 2019, while everything worked correctly on Huawei MediaPad T3. In my case window focus was the problem, it was lost at some point during startup.
So as others have suggested, add this after device ready: document.addEventListener('backbutton', () => {}, false);
In addition at some point after launch in a Java plugin (after the splash screens): this.cordova.getActivity().getWindow().getDecorView().requestFocus();
This is also what Cordova does in CordovaActivity.onResume. If your back button works correctly after suspending and resuming the app, but not before that, this should fix your problem.
Upvotes: 1
Reputation: 5095
I have used as below:
if(cordova.platformId === "android") {
document.addEventListener("backbutton", function (event) {
event.preventDefault();
var confirmStatus = confirm("Do you want to exit?");
if (confirmStatus === true) {
navigator.app.exitApp();
}
}, false);
}
Upvotes: 1
Reputation: 395
I am using this code in my apps:
document.addEventListener("backbutton", function(e) {
e.preventDefault();
return;
}, false);
Note, to run this code when device is ready
Upvotes: 0