首页 文章

BackButton事件会影响PhoneGap中的其他页面

提问于
浏览
0

在我的PhoneGap android应用程序中,在 OnDeviceReady() 方法的Index.html页面中,我为backbutton事件监听器添加了以下函数 .

document.addEventListener("backbutton", function(e) {
          var sPath=window.location.pathname;
          var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
          if(sPage == "index.html"){
                e.preventDefault();
                // My action
                return false;

            } else {
                return true;
            }
    }, false);

Problem Facing:
在我的HomePage(Index.html)它的工作正常 . 如果我按后退按钮它会关闭 .
但是在所有其他页面(Page1.html,Page2.html,Page3.html,Page4.html)中,我没有创建后退按钮事件监听器,但是当我按回键时没有任何反应 .

1 回答

  • 1

    您可以尝试添加以下javascript代码:

    document.addEventListener("backbutton", function(e) {
              var sPath=window.location.pathname;
              var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
              if(sPage == "index.html"){
                    e.preventDefault();
    //  Method to close Phonegap application
                     navigator.app.exitApp();
    
    
                    } else {
       // Method to go back to previous page 
                        navigator.app.backHistory();
                    }
            }, false);
    

    替代方法肯定有效,但使用两个JavaScript文件...

    我对index.html以外的页面使用了以下代码:

    // Wait for Cordova to load
    
         document.addEventListener("deviceready", onDeviceReady, false);
           // Cordova is ready
    
        function onDeviceReady() {
        document.addEventListener("backbutton", function(e){
        e.preventDefault();
        navigator.app.backHistory();
        return false;
    }, true);
    
            }
    

    在主页上,您可以添加navigator.app.exitApp();并删除navigator.app.backHistory();

    已经在这里回答:PhoneGap - android exit on backbutton

相关问题