在Cordova Android应用程序上使用后退按钮关闭模式窗口

Close Modal Window with back button on Cordova Android app

本文关键字:按钮 窗口 模式 Android Cordova 应用 应用程序 程序上      更新时间:2023-09-26

我正在使用Bootstrap 3为HTML和CSS构建一个Cordova web应用程序。我只使用一个index.html文件,在其中我使用Modal窗口执行特定操作。

从应用程序的一些初步测试来看,当模式窗口显示时,最自然的做法是使用手机上的后退按钮关闭它。然而,当他们按下这个按钮时,它会关闭应用程序。

我试图以一种基本的方式处理后退按钮事件,但它似乎在模拟器或我的开发手机上都不起作用(如果华为Y300有区别的话)。下面是代码:

// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
    app.receivedEvent('deviceready');
    // Cordova is loaded and it is now safe to call Cordova methods
    //
    function onDeviceReady() {
        // Register the event listener
        document.addEventListener("backbutton", onBackKeyDown, false);
    }
    // Handle the back button
    //
    function onBackKeyDown() {
        // whatever you want to do
        alert('Back button Pressed');
    }
},

我很确定我知道该怎么做才能知道Modal窗口是否打开,所以我可以自己处理。然而,试图控制后退按钮我做不到。

查看了代码后,我认为它放错了地方。因此,我在index.js文件中添加了以下内容:

document.addEventListener("backbutton", onBackKeyDown, false);
function onBackKeyDown(event) {
    event.preventDefault();
    if($("#myModal").hasClass('in')) {
        $("#myModal").modal('hide');
    } else if ($('body').hasClass('mme')){
        $('body').removeClass('mme');
    } else {
        navigator.app.exitApp();
    }
}