Using the PhoneGap Back Button to gracefully exit the Application

My current project involves developing Mobile Apps using PhoneGap (Cordova 2.2), JQuery, and Javascript. The landing page is the Login Page. However, after successfully logging in and reaching the Dashboard Page, pressing the BACK BUTTON redirects me back to the login page instead of staying on the dashboard. Any suggestions on how to fix this issue would be greatly appreciated.

I have attempted the following:

SCRIPT

<head>
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script type="text/javascript" charset="utf-8">

// Call onDeviceReady when Cordova is loaded.
//
// At this point, the document has loaded but cordova-2.2.0.js has not.
// When Cordova is loaded and talking with the native device,
// it will call the event `deviceready`.
//
function onLoad() {
    document.addEventListener("deviceready", onDeviceReady, false);
}

// 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() {
    alert("Back Button Clicked"); //called the alert..checking
}

</script>

HTML

<body onload="onLoad()">
</body>

For some reason, my onDeviceReady and onBackKeyDown functions are not being triggered. Could I be overlooking something???

Answer №1

To verify if a user is logged in, use the 'loggedin' variable and perform actions within the callback function.

function onBackKeyDown(evt) {
     evt.preventDefault();
     evt.stopPropagation();
     if(loggedin=='yes'){
         // Do nothing or display a popup
     }else{
         history.back();
     }
}

Make sure to bind the event listener first and call app.initialize() in the onPageLoad or $(document).ready() method.

 var app = {
 // Application Constructor
   initialize: function() {
       this.bindEvents();
   },

   // Bind any events that are required on startup. Common events are:
   // 'load', 'deviceready', 'offline', and 'online'.
   bindEvents: function() {

      document.addEventListener('deviceready', this.onDeviceReady, false);

   },

   onDeviceReady: function() {
       document.addEventListener("backbutton", onBackKeyDown, false);
   }
};

Answer №2

Give this a shot

// Upon successful authentication
    localStorage.setItem('authenticated', 1);
// Back button function callback
    function onBackClick(e) {
        e.preventDefault();
        e.stopPropagation();
        var isAuthenticated = localStorage.getItem('authenticated');
        if (isAuthenticated){
            // Stay on current page
        } else {
            history.back();
        }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble utilizing NPM package within AWS Lambda environment, encountered issue with require() function

Recently, I developed a simple NPM package consisting of just two files. Here is the content of index.js: module.exports = { errors: { HttpError: require('./src/errors').HttpError, test: 'value' } } And here& ...

What steps must be taken to display a div element upon clicking an object or entity within an Aframe scene?

Experiencing some coding issues that I could use help with. As a newcomer to Javascript, I might be making a beginner's error here. My goal is for the red tree on the globe in my example to trigger a red div box when clicked. Despite my efforts, I kee ...

Creating a Visual Presentation with Background Image Transition in HTML, CSS, and JavaScript

Seeking assistance in setting up a basic background image slideshow on my website. I have been unable to locate a suitable tutorial online, so I'm reaching out here for guidance. HTML: <body> <h3>Welcome!</h1> <p>Lorem i ...

How to dynamically change the title of a group box in Angular 8 using TypeScript

I am working with a component that includes a groupbox: <fieldset> <legend>Title</legend> </fieldset> Could I change the title of the groupbox using TypeScript code? ...

Slideshow development with code

This is the code I currently have: HTML: <head> <title>JQuery demo</title> <script type="text/javascript" src="scripts/jQuery.js"></script> <script type="text/javascript" src="scripts/slider.js"></script ...

Enhance your horizontal stacked bar chart in chart.js by incorporating inner labels with the help of the 'chartjs-plugin-labels' plugin

Currently, I have integrated a package that allows me to incorporate labels into my charts - import * as pluginDataLabels from "chartjs-plugin-labels"; While it works perfectly fine with line charts, pie charts, and normal bar charts, I am facin ...

An unexpected error occurred in the Ember route processing: Assertion Failed in the listing

After working diligently to integrate an Emberjs front end (utilizing Ember Data) with my Flask API backend, I have encountered a puzzling issue. Despite the adapter functioning correctly - as evidenced by the API being called when accessing the 'List ...

Sending an image from a NodeJS socket server to another server: The ultimate guide

Hello there, I'm currently working on a new project and I could really use your input on a challenge I'm dealing with. Here's the situation: I have a web server running a socket.io module. The server is listening on port 3012 and streaming ...

The issue with the Angular custom checkbox directive arises when using it within an ng-repeat

A personalized directive has been developed for checkboxes that is applicable throughout the application. The code for creating the checkbox is as follows: JS angular.module("myApp") .component("ngCheckbox", { template: '<di ...

The URL being called by $http.get is incorrect

Attempting to invoke a URL through my AngularJS service, I have encountered an issue where a particular call is not reaching the intended URL. The following code snippet depicts the function responsible for making the call, along with a console.log statem ...

Learn how to use canvas and JavaScript to draw lines that display x and y coordinates on top of the mouse pointer at the same time

Implement a functionality in which lines are drawn while the mouse button is held down and simultaneously display x & y coordinates on top of the mouse pointer during mouse movement using canvas and JavaScript. The issue arises when attempting to draw lin ...

What are some methods to implement overflow:hidden for stacked images inside a div?

I currently have two images stacked on top of each other within a div element as shown below: <div class="container"> <img src="somepic.jpg" class="layer" /> <img src="otherpic.jpg" class="layer" /> </div> Styling is set u ...

Every time I try to request something on my localhost, NextJS console throws a TypeError, saying it cannot read the properties of undefined, specifically '_owner'

Update: I've noticed that these errors only appear in Chrome, while other browsers do not show them. Recently, I created a simple NextJS project by following a couple of tutorials, which also includes TypeScript. However, after running npm run dev, I ...

Transform a formatted currency amount into a double value by utilizing regex

I need to convert various currency formats into a double value. For example: 1,000,000.00 => 1000000.00 2'345',00 => 2345.00 2'344'334.03 => 1000000.03 The current solution I have is functional but inefficient. I am explorin ...

The ivory pillar on the far right extending over the entire width of the page

Struggling with Bootstrap to create responsive cards, I encountered a white column that's extending off the page and causing an annoying scroll to the right. Can anyone assist me in resolving this issue? If you have any suggestions on how to achieve ...

The server returned a response that was void of any content

I have encountered an issue while trying to retrieve data from my server. The request works perfectly fine when tested with Postman, returning the expected data. However, upon implementing the request in my application, I receive an empty object with prope ...

running a prompt command from my PHP/HTML script

I currently run a puppeteer program by typing c:\myProgram>node index.js in the command prompt. However, I would like to automate this process through my PHP program instead of manually entering it each time. Something similar to this pseudo-code ...

zod - Mastering the Art of Dive Picking

Working with zod and fastify, my UserModel includes the username and device properties. The username is a string, while the device consists of "name", "id", and "verified" fields in an object (DeviceModel). For the sign-up process, I need to return the co ...

Paste the current webpage's URL into a fresh alert popup using javascript"

I found myself spending hours trying to figure out the best way to create a JavaScript function that would copy the current URL and display it in a new alert window. Imagine a scenario where a user clicks on "Share this page" and a new alert window pops u ...

Tips for keeping data on a page up-to-date using Node.js and Express

Currently delving into the world of Node.js and Express, I am immersed in a project that involves pinging websites and exhibiting the results on a web page. Leveraging HoganJS for templating as well. My primary focus is to decipher the steps necessary to m ...