Is it possible to simulate Android “hardware” back

2019-05-01 03:30发布

问题:

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:

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);
    }
});