可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a phonegap app that requires I capture the back button. This works swimmingly but when I am at the main screen and the back button is pressed I want to call the original event handler and let the app close or do whatever comes naturally to the platform with such a press. I know I can tell the app to quit but understand this is bad form for iPhone apps.
No matter what I try (and I have tried many things) I cannot get the original handler to fire. Any advice?
In my code I have a switch statement inside my backbutton event handler that directs the app as needed to the effect of:
switch blahBlah { case 'this' : doThis() ; break; case 'main' : // What do I do here that is well behaved for all platforms??? break; default: doFoo() ; }
回答1:
Detect whenever you land on the main screen and remove your custom event handler.
document.removeEventListener( "backbutton", function(){}, false );
and add the event listener on the other pages (or sections).
document.addEventListener( "backbutton", OverrideBackButton, false );
Hope that helps.
回答2:
This is what I've used and it seems to work fine for my needs
function pageinit() { document.addEventListener("deviceready", deviceInfo, true); } function deviceInfo() { document.addEventListener("backbutton", onBackButton, true); } function onBackButton(e) { try{ var activePage = $.mobile.activePage.attr('id'); if(activePage == 'Options'){ closeOptions(); } else if(activePage == 'Popup'){ closePopup(); } else if(activePage == 'HomePage'){ function checkButtonSelection(iValue){ if (iValue == 2){ navigator.app.exitApp(); } } e.preventDefault(); navigator.notification.confirm( "Are you sure you want to EXIT the program?", checkButtonSelection, 'EXIT APP:', 'Cancel,OK'); } else { navigator.app.backHistory(); } } catch(e){ console.log('Exception: '+e,3); } }
Hope this helps...
回答3:
Cordova 7.x, at least on Android, doesn't seem to properly update the override state. As a consequence, @SHANK's answer doesn't work anymore.
As a workaround, you can disable back button overriding manually, resulting in default behavior:
navigator.app.overrideBackbutton(false);
To re-active custom handling, analogously do:
navigator.app.overrideBackbutton(true);
I filed a bug report on Apache's issue tracker regarding this.
回答4:
An easy and smooth way to do it could be something like this, this statement worked in my case:
if($("#mainPage").is(".ui-page-active")){ navigator.app.exitApp(); }
I am using jQuery: http://demos.jquerymobile.com/1.0a3/docs/api/globalconfig.html
regards :)