9
votes

It's great that it's possible to test many cases in a Cordova/Ionic app in the browser. But I haven't yet found a way to fake pressing Android's (formerly hardware-) back-button.

Would be nice to have an extra drawer with a back-button or a key combination (e.g. Alt+Ctrl+<) which triggers an event that makes Ionic think the Android back-button was pressed.

Is it possible to trigger such event with JavaScript? How?

To be clear: I only want this when testing ionic apps in my web-browser. So you Android guys: no need to provide Java code here - we're not on an Android device or emulator. And: I'm pretty sure something like $ionicHistory.goBack() or $window.history.back() is not what I want.

1
Good question, upvoted. Probably that would have to be a request to Ionic team, but they just may say "use emulator" ;)Nikola
not sure if this will work, but you can try to fire the backbutton event: cordova.fireDocumentEvent('backbutton');jcesarmobile
@jcesarmobile good idea - I'll try that (hopefully soon).hgoebl
Thanks @jcesarmobile it works. I just had to remove dependency to cordova, so I had to code a few more lines.hgoebl
cordova.fireDocumentEvent('backbutton'); works like charmgarg10may

1 Answers

11
votes

I have a working solution I'd like to share with you. When pressing Alt+Ctrl+< it triggers the backbutton event. Of course such things like navigator.app.exitApp() won't work, but simple navigation works, e.g. closing modals.

AppModule.run(function ($window, $document, $ionicPlatform) {
    'use strict';
    var document = $document[0];

    function triggerBackButton() {
        var backButtonEvent = document.createEvent('Events');
        backButtonEvent.initEvent('backbutton', false, false);
        document.dispatchEvent(backButtonEvent);
    }

    function registerBackButtonFake() {
        document.addEventListener('keyup', function (event) {
            // Alt+Ctrl+<
            if (event.altKey && event.ctrlKey && event.keyCode === 188) {
                triggerBackButton();
            }
        });
    }

    if (!$window.cordova) {
        $ionicPlatform.ready(registerBackButtonFake);
    }
});