Search code examples
cordovamobilehybrid-mobile-appback-buttononsen-ui

cordova back button fires event listener but app closes anyway


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.


Solution

  • 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);
    });