【问题标题】:Close cordova app on back button关闭后退按钮上的科尔多瓦应用程序
【发布时间】:2015-04-30 06:14:51
【问题描述】:

我的移动应用程序使用 cordova 和 angular.js 有以下逻辑

在 index.html 中包含的 mobile.js 中处理我的逻辑,例如将文件保存在 sdcard 上,然后使用将用户重定向到第二个 html 页面

window.location.href="main.html";

它将使用mobile.js放入sdcard中的文件

我面临的问题是,当我在 main.html 的主页上并且用户按下后退按钮时,它会返回 index.html 文件,然后在处理后返回 main.html 而不是应用关闭。

我尝试使用带有“后退按钮”事件监听器的 history.length 对象

        document.addEventListener('deviceready',function(){
        document.addEventListener('backbutton',function(e){
            console.log("history is "+history.length);
            if(history.length==1){
                e.preventDefault();
                navigator.app.exitApp();
            }
            else{
                navigator.app.backHistory();
            }
        },false);
    },false);

但是返回的时候长度并没有减少,只是增加了,所以app返回到index.html。(history.length总是大于1)

我已经查看了可用的解决方案,例如

document.addEventListener("backbutton", function(e){
if($.mobile.activePage.is('#homepage')){
    /* 
     Event preventDefault/stopPropagation not required as adding backbutton
      listener itself override the default behaviour. Refer below PhoneGap link.
    */
    //e.preventDefault();
    navigator.app.exitApp();
}
else {
    navigator.app.backHistory()
} 
}, false);

但是使用它的问题是,如果用户去

second-page->homepage->third-page->homepage

应用程序将退出,但应转至第三页。

【问题讨论】:

    标签: android angularjs cordova


    【解决方案1】:

    您可以使用 jQuery 移动页面加载事件来保留您自己的历史列表,当您返回时,其长度确实会减少。像这样的东西(未经我的头脑测试,所以可能不完全正确):

    var pageHistory = [];
    
    $(document).on("deviceready", onDeviceReady);
    
    
    function onDeviceReady(){
        $(document).on("pagecontainerload", onPageLoad);
        $(document).on("backbutton", onBackButton);
    }
    
    function onBackButton(e){
        e.preventDefault();
        pageHistory.pop();
        if(pageHistory.length==0){
            navigator.app.exitApp();
        }
        else{
            navigator.app.backHistory();
        }
    }
    
    function onPageLoad(e, ui){
        var pageId = ui.toPage.attr('id');
        if(pageId !== pageHistory[pageHistory.length]){
            pageHistory.push(pageId);
        }    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-30
      • 2019-03-08
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      相关资源
      最近更新 更多