cordova back button fires event listener but app c

2019-09-04 03:31发布

问题:

I have the following code where if the user presses back button on his device, I want to show him a popup before he is able to exit the app. However, this does not work for me. The alert box is showed but the app also closes.

document.addEventListener("deviceready", function() {
    document.addEventListener("backbutton", function(e) {
        e.preventDefault();
        $scope.alertDialog.show();
    }, false);
}, false);

Cordova version:6.4.0 And before someone brings it out - cordova.js is included in the index html page. UI is built using onsenUI with angularJS v1.

回答1:

Figured it out. How to control android backbutton routes? The last 0 voted answer is the right one.

You can controll it with "disableDeviceBackButtonHandler" after ons.ready event. After that add a event listener for back button and do anything you want.

ons.ready(function() {
  ons.disableDeviceBackButtonHandler();

  // Use Cordova handler
  window.document.addEventListener('backbutton', function() {
    // Handle backbutton event
  }, false);
});


回答2:

You can do like following:

document.addEventListener("deviceready", function() {
var backbutton=0;
    document.addEventListener("backbutton", function(e) {
       if(backbutton==0){
            backbutton++;
              $scope.alertDialog.show();
             // window.plugins.toast.showShortCenter('Press again to exit');
            $timeout(function(){backbutton=0;},5000);
        }else{
            navigator.app.exitApp();
        }
    }, false);
}, false);

Hope it will help you.