Search code examples
javascriptandroidcordovahybrid-mobile-appback-button

Cordova back button is not working on the first launch of android app


I am using Cordova 6.x to build Android app(6.0). I have overridden the back button functionality using event listener. But this event listener is called on the first time launch of the app. But if I kill the app and relaunch, this event listener is called on pressing back button.

index.html

...
<script src="cordova.js"></script>
<script type="text/javascript" src="app.js"></script>
<body ng-app="app" ng-controller="appController">
...

app.js

...
angular.module('app', []).controller("appController", function($scope) {

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

    function onDeviceReady()
    {
       console.log("On device ready called");
       document.addEventListener('backbutton', onBackButton, false);
    }

    function onBackButton()
    {
         console.log("Back button pressed");   
    }
});
...

When I first time launch the app after installation, log has "On device ready called". But if I relaunch the app and press back button, log has "On device ready called" as well as "Back button pressed". Any help will be much appreciated.


Solution

  • Please try manually bootstrap angular and see if backbutton function works correctly.
    So, something like...

    document.addEventListener("deviceready", function() {
        angular.bootstrap(document, "YourApp"); 
        document.addEventListener('backbutton', onBackButton, false);
    
        function onBackButton()
        {
           console.log("Back button pressed");   
        }
    }, false);