问题
I am using ionic to develop hybrid app. But recently I found that whenever I click on the hardware back button, the app will exit no matter on which page. I tried to add the following code, it does shows the alert box but this doesn't stop the app from exit (alert box is not clicked).
$ionicPlatform.onHardwareBackButton(function() {
alert("click on hardware back button");
}
How can I prevent the app from exit from hardware back button?
回答1:
Normally the apps exists when you're on a root view and there's no history on the stack.
You can intercept the event registerBackButtonAction and cancel the action.
The registration of the even must happen when you run your app:
.run(function($ionicPlatform) {
$ionicPlatform.registerBackButtonAction(function(e) {
e.preventDefault();
}, 1000);
});
This is the signature:
registerBackButtonAction(callback, priority, [actionId])
As you can see there's a priority as second parameter. According to the documentation:
The priorities for the existing back button hooks are as follows:
Return to previous view = 100
Close side menu = 150
Dismiss modal = 200
Close action sheet = 300
Dismiss popup = 400
Dismiss loading overlay = 500
Your back button action will override each of the above actions whose priority is less than the priority you provide. For example, an action assigned a priority of 101 will override the 'return to previous view' action, but not any of the other actions.
I've use 1000 to override each of the other actions. It's always better to register and listen to this even as you might want to check the event before cancelling the event. If you follow this path and at some point your app become more complex with some sort of navigation, you won't be able to exit your app.
来源:https://stackoverflow.com/questions/32900211/ionic-prevent-exit-app-on-hardware-back-button