Apache Cordova backbutton event not fired on Windows Phone (universal)

1.1k views Asked by At

I've creeated an Apache Cordova project for a single page application. On the start page there is a list of items. When I click on a item I navigate to the details page with

window.navigate("#/details/" + id); 

Angular.js displays the details template but when I use the hardware backbutton on a windows phone it suspends the application instead ov navigating back. So I tried to hook up to the backbutton event

function onDeviceReady() {
    // Handle the Cordova pause and resume events
    document.addEventListener('pause', onPause.bind(this), false);
    document.addEventListener('resume', onResume.bind(this), false);
    document.addEventListener("backbutton", onBackButton, false);
}

but this event isn't even fired when I click the back button. I also use WinJS and tried WinJS.Application.onbackclick but even this doesn't work.

So how can I handle the back button on Windows Phone universal?

3

There are 3 answers

3
Rob Caplan - MSFT On

This looks like a bug in the Windows Phone Runtime target for Cordova. In Silverlight the CordovaPage.xaml.cs file hooks up the Windows Phone BackButton event handling and forwards it to Cordova's backButton event.

This doesn't happen in the Runtime version, so you'll have to add your own platform specific handling either by handling WinJS's onbackclick event or the Windows.Phone.UI.Input.HardwareButtons.BackPressed event.

0
tvelop On

This worked for me...

function onBackPressed(eventArgs) {
   eventArgs.handled = true;
   /* Your behaviour/navigation */
}

Windows.Phone.UI.Input.HardwareButtons.addEventListener("backpressed", onBackPressed);

To prevent default behaviour (e.g. suspending the app):

eventArgs.handled = true

More Information: HardwareButtons.BackPressed

0
scripter On

Windows Phone WinJS onbackclick needs to return true or false depending on if you want to exit your app (when you've navigated all the way back and finally do want to exit) or not.

//for not Windows Phone users
document.addEventListener("backbutton", function () { goBack(); }, false);
//for Windows Phone users
if (Windows && WinJS){
    WinJS.Application.onbackclick = function (event) { 
        event.handled = true;
        return goBack(); 
    };
}

goBack function returns true when it executes and false when it can't go back any further.

var backstack = 0;
function goForward(){
    backstack++;
    //additional navigation code
};
function goBack(){
    //show hide back arrow
    if (Windows && WinJS) {
        var currentview = Windows.UI.Core.SystemNavigationManager.getForCurrentView();
        currentview.appViewBackButtonVisibility = backstack < 1;
    }
    if(backstack > 1) {
        backstack--;
        //additional back navigation code
        return true;
    }
    else return false;
};