如何仅在 cordova 4.0 的单个页面上覆盖后退按钮?

How to override back button only on single page in cordova 4.0?

我有一个要求,只有在特定页面上,我的意思是当用户说 index.html 并且当他点击后退按钮时,我需要提示一个警告说你想退出一个应用程序。 如果他说 'yes',退出 else 'no'。我可以通过覆盖后退按钮并检查用户是否在 index.html 页面中来实现这一点,如下面的代码所示。

代码示例:

function onLoad() {
    alert("OnLoad");
    document.addEventListener("deviceready", onDeviceReay, false);
}
 function onDeviceReay()
        {   
            var x = document.URL;
            alert(x);
    if( x.indexOf('index') >= 0)
    {
            document.addEventListener('backbutton', function(e){
                      if (confirm("Press a button!"))
                      {
                     alert("You pressed OK!");
                     navigator.app.exitApp();
                      }
                    else
                      {
                        alert("You pressed Cancel!");
                      }
              }, false);
        }
        }

但问题是当用户导航到其他页面,然后当他单击后退按钮时,它不会导航回上一个 page.Could 请有人指出我哪里出错了。谢谢。

将以下内容放在 html 页面中需要触发后退按钮的位置:

document.addEventListener("backbutton", leavePage, false); 

    function onPageLeave(buttonIndex) {

        if(buttonIndex==1){
            window.history.back();
        }
        else{   
        }
    }

    function leavePage() {
        navigator.notification.confirm(
            'Would you like to leave  ?', // message
             onPageLeave,            // callback to invoke with index of button pressed
            'Leaving page request',           // title
            ['Yes','No']         // buttonLabels
        );
    }

请注意,您需要通知插件。否则你可以用一个简单的 alert() 替换。