Search code examples
javascripthtmlcordovaphonegap-plugins

How to Replace the Main Page in Cordova?


I made login function so when the users login it will navigating to other page, but the problem is after login succes the users can go back to login page again just with press the physical back button. Now what i want is after login the users cant go back to login page again, so when the physical back button pressed it will close the app instead. here is my onloginsucces method

document.getElementById('auth').onclick = function () {
$fh.auth({
  "policyId": "policyid",
  "clientToken": "appid",
  // Your App GUID
  "endRedirectUrl": window.location.href,
  "params": {
    "userId": document.getElementById('username').value,
    "password": document.getElementById('password').value
  }
}, function(res) {
  // Authentication successful - store sessionToken in variable
  var sessionToken = res.sessionToken;
  alert("Login Succes");
  window.location = './menu.html';

}, function(msg, err) {
  var errorMsg = err.message;
  if (errorMsg === "user_purge_data" || errorMsg === "device_purge_data") {
    // User or device has been black listed from administration console and all local data should be wiped
  } else {
    alert("Authentication failed - " + errorMsg);
  }
})
};

is there anyway beside using window.location to navigating ? like window.replace maybe , thanks?

UPDATE

<head>
    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

    <title>Hello World</title>

    <link rel="stylesheet" href="css/app.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type="text/javascript" src="cordova-2.7.0.js"></script>
    <script type="text/javascript" src="js/jquery.min.1.9.js"></script>
    <script type="text/javascript" src="js/jquery.mobile-1.3.1.min.js"></script>

    <script type="text/javascript">
        function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
        }

        // device APIs are available
        //
        function onDeviceReady() {
            // Register the event listener
            document.addEventListener("backbutton", onBackKeyDown, false);
        }

        // Handle the back button
        //
        function onBackKeyDown() {
            e.preventDefault();
        }
        </script>
  </head>

Solution

  • try below:

    document.addEventListener("backbutton", onBackKeyDown, false);
       function onBackKeyDown(e) {
       #or return False
       e.preventDefault();
    }
    

    that function disables the buttons functionality. I pulled this from a page found a while back on stackoverflow page. I think return False works fine but is probably not JS proper usage.

    edit thanks to commenters: Note this needs to be in Cordovas on device ready listener to work.