Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to simulate Android "hardware" back-button in web browser?

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.

like image 906
hgoebl Avatar asked Jul 17 '15 05:07

hgoebl


People also ask

What is hardware back button in Android?

The hardware back button is found on most Android devices. In native applications it can be used to close modals, navigate to the previous view, exit an app, and more. By default in Ionic, when the back button is pressed, the current view will be popped off the navigation stack, and the previous view will be displayed.

How do you use the back button in ionic 5?

The back button navigates back in the app's history upon click. It is smart enough to know what to render based on the mode and when to show based on the navigation stack. To change what is displayed in the back button, use the text and icon properties.


1 Answers

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);
    }
});
like image 177
hgoebl Avatar answered Sep 18 '22 13:09

hgoebl