Phonegap Android Back Button w/ Ionic and Angular

2019-07-31 09:59发布

I'm having issues disabling the back button for Android in a Phonegap project using Ionic Framework / Angular JS. I have tried many other proposed solutions to no avail. The problem is I have a 'Login' screen which is a modal (ionicModal), but Android users are able to use the back button to navigate away regardless of if they are logged in or not.

I tried disabling the Android Back button all together. The event fires, but the page navigation still happens. I feel like if this worked, this would be the ideal and most straight forward solution. Here though, preventDefault() and stopPropagation() seem to have no effect.

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    document.addEventListener("backbutton", onBackKeyDown, false);
}

function onBackKeyDown(e) {
    alert('back button triggered');
    e.preventDefault();
    e.stopPropagation();
}

I also tried disabling the navigation from within Angular by listening to $locationChangeStart and preventing that:

// Disable "Back" button on androids if user is on login screen
$rootScope.$on('$locationChangeStart', function(e) {
    if( true ) {
        e.preventDefault();
        e.stopPropagation();
    }
});

This also seems to work, but yet somehow still does not prevent Android from hiding the modal and going to the previous screen.

Is there a proper way to disable the Android Back button when using Phonegap/Ionic/Angular? It uses the Angular UI router, and the modal is not a route but rather an ionicModal.

2条回答
Luminary・发光体
2楼-- · 2019-07-31 10:56

After starting to dig around the ionic code in GitHub, I saw they've recently added this as an option to the modal. I was able to apply only the changes highlighted in this commit and get this working:

https://github.com/driftyco/ionic/commit/61f879bb535997078f73b7faa424e43699e0b018

Also add the following constant, per commit https://github.com/driftyco/ionic/commit/e9d8eba12b4de48617e9335e113c7c98173909b7

var PLATFORM_BACK_BUTTON_PRIORITY_MODAL = 200;
查看更多
迷人小祖宗
3楼-- · 2019-07-31 11:01

seems that there is a boolean property named "hardwareBackButtonClose" that you can set on the modal to determine whether the modal can be closed using the hardware back button on Android and similar devices. Defaults to: true, so try setting it to false.

查看更多
登录 后发表回答