cordova back button fires event listener but app closes anyway

对着背影说爱祢 提交于 2019-12-12 06:37:48

问题


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.



来源:https://stackoverflow.com/questions/40283209/cordova-back-button-fires-event-listener-but-app-closes-anyway

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!