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

跟風遠走 提交于 2019-12-22 04:55:09

问题


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


来源:https://stackoverflow.com/questions/31469207/is-it-possible-to-simulate-android-hardware-back-button-in-web-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!