What are the steps to keep a web application from closing on Android when the back button is pressed?

I am currently working on a HTML5 web application and packaging it with Cordova (phonegap) 1.7.

My goal is to customize the behavior of the Android back button so that instead of closing the application by default, it navigates back using window.history.back(). How can I prevent Android from terminating the default activity when the back button is pressed?

I have noticed that the "Back button pressed!!!!" message appears in the logcat before the application closes, indicating that the method is being executed beforehand.

Here is what my code looks like at the moment:

// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);

// Cordova is ready
//
function onDeviceReady() {

    document.addEventListener("backbutton", function(e) {

        console.log("Back button pressed!!!!");                 
        window.history.back();


    }, false);

}

EDIT: I am open to any suggestions on how to simulate the functionality of window.history.back() directly from the DefaultActivity.java Android class, if such an approach is feasible!

Answer №1

After some trial and error, I managed to resolve the issue by incorporating the following snippet into the MainActivity.kt file to override the default android behavior while retaining the original JavaScript code mentioned in the query:

@Override
public void onBackPressed() {
   return;
}

For anyone encountering a similar dilemma in the future, I hope this solution proves useful!

Answer №2

My approach to handling the back button event was similar. I checked if it was the first page and then prompted the user to confirm exiting the program, depending on the state of the program. I didn't feel the need to add the override as shown.

if ($.mobile.activePage.attr('id') === 'firstpage') {
    // Prompt to confirm the exit
} else {
  window.history.back();
}

If the user wants to exit, you can use:

navigator.app.exitApp();

You probably still want to give users the option to exit your app. Apps that don't allow an exit are not very user-friendly in my opinion.

I hope this solution works for you.

Answer №3

I've never personally had to perform that action, but have you considered using the statement return true?

For example, in the context of the Java SDK, returning True signals to the system that the event has been successfully handled and should not be passed on to additional event listeners.

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

Mongoose encountering an issue with undefined properties (specifically 'prototype') and cannot read them

I am currently using Mongoose 7.0.1 on Next JS 13.2.2 and React 18.2.0. After tirelessly searching for a solution to my problem, I am still struggling with connecting to a MongoDB. Every time I try to import mongoose into my project for the connection, an ...

Ways to enhance background removal in OpenCV using two images

I am currently using OpenCV in conjunction with NodeJS (opencv4nodejs), and I am working on a project that involves replacing the background of webcam images. I have one image with a person's head in the frame, and another without. My code is functio ...

Symfony2: Using Ajax to send data to a controller

I have implemented a search input on my website that allows users to search for content within my database. I want this search input to function similarly to the search bar on Facebook, using Ajax for instant searching. Despite trying various code snippets ...

The transformation of a Blender model in THREE.js results in a completely new and distinct

I have a Blender model that I'm trying to integrate into my website using THREE.js, but I'm encountering issues with the GLTF file rendering. The model appears broken with missing elements, misplaced objects, and incorrect lighting. I've tes ...

Using Ajax, the script triggers calls upon detecting keyup events on various input fields, each

I'm encountering issues while attempting to solve this logic puzzle. The page contains multiple fields and the goal is to store the input values in the database when the user finishes typing. Here's the code snippet: var debounce = null; ...

Attempting to iterate through and retrieve the names listed in the table

I have a code that I need help with in extracting names from td elements using jQuery. In certain instances, if the td is empty, I want to merge the left-side td with the 5 right-side tds because the first td on the right side is empty and the second td c ...

Having trouble getting the ValidatorPipe to function properly in my nest.js application

Issue Description There is an issue with the current behavior where initializing a validation pipe for a request body does not reject invalid types as expected. Desired Outcome The expected behavior should be that when a user provides a value that does n ...

What is the best way to access a variable from a class in ES6?

Hey there, I'm having trouble accessing the variable from the KeyCodeClass. Let me walk you through what I've tried so far: Attempt 1 class KeyCodeClass1 { constructor() { this.space; } KeyDown(e) { if (e.keyCode == 3 ...

Having trouble with filtering an array using the some() method of another array?

When utilizing the code below, my goal is to filter the first array by checking if the item's id exists in the second array. However, I am encountering an issue where the result is coming back empty. dialogRef.afterClosed().subscribe((airlines: Airli ...

Retrieve the names contained within TD elements using the console

I always enjoy experimenting with new things. Take a look at the https://lodash.com/docs/4.17.15 lodash documentation site where you'll find a menu on the left side featuring all available functions. Is there a way to extract the names of these functi ...

"Is there a way to transfer a value from one list box to another without needing to refresh the page, by utilizing AJAX,

Is there a way to automatically load Related Course levels in the Course Level Listbox when selecting a Course from the Course list? <script type="text/javascript" src="js/jquery.js"></script> <div>Course:<select name="course_id" id= ...

Is it possible to observe cross-domain Javascript requests in Firebug or any alternative browser extension?

Is there a way to monitor cross-domain JavaScript requests made on a webpage? Is it possible with Firebug or any other plugin? Consider this scenario: If I visit stackoverflow.com and they incorporate an external JavaScript file (such as Google Analytics) ...

Is there a way to generate a button that displays the subsequent 5 outcomes from the database without navigating away from the current

I am looking to implement a button on my webpage that, once clicked, will load the next set of five questions from my database. I prefer not to use pagination or the GET method to prevent users from navigating back to previously answered questions. My goa ...

jQuery registers the enter event, but does not proceed to trigger the enter action

Hey there, I've been experimenting with jQuery to capture the enter event. Something peculiar is happening though - after pressing enter in the text area, an alert pops up but the text gets entered only after that. Despite trying various solutions, I ...

What is the method to define a function in express js that is accessible from all views?

Is there a way to develop a function within my Express JS MVC web application that can be accessed from any view? How can I define this function in middleware so it can be directly called from a view? I envision being able to use this function like: < ...

Updating a nested object within an array in a ReactJs component

I am struggling with updating a nested object within an array in the state of my React application. My goal is to determine if an item already exists in the state based on its name. Here's what I'm aiming for: Add an item to the cart. If th ...

Bringing Angular ECharts into a Stackblitz 15.1 setup: A How-To Guide

Recently, Stackblitz made a change to use a standalone configuration for Angular Projects. However, when trying to initialize the module for Angular ECharts (ngx-echarts), an error occurred: Error in src/main.ts (18:5) Type 'ModuleWithProviders<Ngx ...

Attempting to update an AJAX field with the returned value, but it only updates after clicking away from it

Image of form utilizing AJAX & JS The current setup involves a maintainer that uses AJAX to update the "Calc" field in response to a number entered in the "Order No" field. The issue is that the "Calc" field does not update immediately after typing in the ...

After performing a Vuex action on one Vue.js component, the update is not reflected on another Vue

I am facing an issue with a component that renders a booking table. When I update my store in another component, the table does not get updated even though the store and computed properties are updated. I suspect that the problem lies with the filter not b ...

Experience choppy scrolling in Internet Explorer

Check out my click and drag scrolling Image Viewer here. While it functions perfectly in Firefox and Chrome, Internet Explorer is giving me some trouble. The movement seems jerky, especially when scrolling diagonally. It's like the scroll is sluggish ...