How to disable android back button handler in ONSE

2019-08-03 16:37发布

问题:

I am developing a phonegap application in ONSEN-UI, in which I want to disable the android back button handler. I've tried Phonegap's backbutton hadler code to disable it. But I am unable to do it. Is there any other way to do it?

My Code:

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

 function onDeviceReady() {

        document.addEventListener("backbutton", function (e) {
        e.preventDefault();
        }, false);
}

回答1:

This is explained in Onsen UI docs: http://onsen.io/reference/ons.html#methods-summary

Just use the method ons.disableDeviceBackButtonHandler() and it will be disabled. You can use ons.enableDeviceBackButtonHandler() to enable it again.



回答2:

This works for me in onsen2...I have it in my app.js

ons.ready(function () {
    ons.disableDeviceBackButtonHandler();
    document.addEventListener('backbutton', function () {}, false);
});


回答3:

Try to leave the function empty. This works perfect for me.

document.addEventListener("backbutton", androidBackKey, false);

var androidBackKey = function(){
	//stay empty
};



回答4:

Try this:

function onLoad() { document.addEventListener("deviceready",onDeviceReady,false); } function onDeviceReady() { document.addEventListener("backbutton",noth,false); } function noth() { }



回答5:

Use this if you're using a navigator:

myNavigator.getDeviceBackButtonHandler().setListener( stopButton );
function stopButton(e) {
    try{
        myNavigator.popPage();
    }
    catch (err){
        // event.callParentHandler();
        console.log( "Stopping...." + e);
    }
}

It's another listener handled by ONSEN-UI itself that quit the app. So add a listener attached to document will not stop the app from exiting. To understand it's flow, you may check out onsenui_all.js to check out the source code.



回答6:

If someone useing onsenUI with VueJS put this code in app's created or mounted method.

this.$ons.ready(() => {

  this.$ons.disableDeviceBackButtonHandler();

  document.addEventListener("backbutton", e => {
    e.preventDefault();
    e.stopPropagation();
  }, false);

});


回答7:

If you've been looking for what I'm looking for, that is disable Android back button exiting the app altogether back to launcher, but preserve back button functionality across the app (to back out to main menu or close a dialog for example), you may do it using that method:

ons.setDefaultDeviceBackButtonListener(function(event) {});

This method overrides default action (which would be normally executed if there's nothing other action to execute), which is normally to close the app in case of Cordova.

Source and more examples: https://onsen.io/v2/guide/cordova.html#device-back-button (there's example there that can show confirmation dialog and exit the app if user says yes)