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

Get the package from a Lerna-managed monorepository using a git URL

Currently working on a project using yarn. The project has a dependency that is part of a larger monorepo managed by lerna. Despite the subpackage being updated, it has not been published yet and I require access to that unreleased code. Is there a method ...

Issue with PassportJS and Express 4 failing to properly store cookies/session data

I have a situation with my Express 4 app using Passport 0.3.2. I've set up a passport-local strategy, and it's successfully retrieving the user information when the /session endpoint is provided with a username and password. The issue arises whe ...

Exploring the concept of union return types in TypeScript

Hello, I am facing an issue while trying to incorporate TypeScript in a way that may not be its intended use. I have created a custom hook called useGet in React which can return one of the following types: type Response<T> = [T, false, false] | [nul ...

Tips on invoking a factory method from a different service method in AngularJS

I have a factory method that goes like this.. (function (angular) { "use strict"; angular .module('app') .factory('UserService', ['$rootScope', '$q', function ($rootScope, $q) { ...

Traverse each child element sequentially using setTimeout or a delay function

Looking to dynamically apply a CSS filter to a list of divs with a delay between each iteration. Here are my attempted solutions: $(this).children().each(function() { $(this).delay(5000).css("-webkit-filter", "brightness(2)"); }); And this alternativ ...

Using AngularJS, you can display repeated elements in a single textarea by utilizing

--> I want to be able to input data into a textarea using just one textarea element. --> The reason for this is so that when the data in MySQL is updated, I can type new data in the textarea while still keeping the existing data. I have tried using ng-re ...

When clearInterval is used to stop a setInterval, it will not automatically restart if reset with setInterval

I am facing an issue with a countdown timer that I have created using setInterval in JavaScript. The timer is supposed to countdown from one minute at one second intervals. However, when I click the "start" button, it starts the countdown but if I click an ...

When utilizing the get method to invoke a JavaScript function, IE imposes a restriction of 2083 characters

I need assistance with passing a lengthy XML string to a JavaScript function. Currently, the process involves using an XSL file to generate HTML code which includes a link that triggers the function like this. <a href="javascript:myFunctionName('l ...

Tips for navigating to a different route during the ngOnInit lifecycle event

How can I automatically redirect users to a specific page when they paste a URL directly into the browser? I would like users to be directed to the /en/sell page when they enter this URL: http://localhost:3000/en/sell/confirmation Below is the code I am ...

Issue with Vue JS function not providing the desired array output

I declared a property in my data model like this: someArray: [] A function returns an array: getMyArray: function (someId) { var result = [7, 8, 9, 10]; return result; } I'm assigning the result of the function to m ...

Exploring the power of Jade and Angular through implementing a for loop within a table structure

I'm brand new to using Jade and Angular, and I could really use a hint from someone more experienced. ... - for (var i = 0; i < p.length; i++) tr td= i + 1 td= price(value='p[i].somedbstuff') ... I want the la ...

Can an additional height be added to the equalizer to increase its height?

Is it feasible to append an additional 35px to the height determined by Foundation Equalizer? For instance, if Equalizer computes a height of 350px, I would like to increase it by 35px. This means that the resultant style should be height: 385px; instead ...

Unable to expand Bootstrap navbar due to collapsing issue

I recently implemented a collapsed navbar on my website using bootstrap. However, I'm facing an issue where it does not open when clicking on the hamburger menu. After researching various solutions for this problem and trying them out, none of them s ...

Sending a JSONP request to a PHP script

For my application submission, I am trying to send a JSON object to a PHP script that will return a JSON response. The challenge here is that the domain does not comply with the same-origin policy, meaning the JSON is being sent from a different domain. Up ...

Can you please explain the purpose of this function?

I came across this code snippet on a website and I'm curious about its function and purpose. While I'm familiar with PHP, HTML, CSS, and JavaScript, I haven't had the chance to learn JQUERY and AJAX yet. Specifically, I'm interested in ...

Tips for deleting a button from a DataTable file upload feature

I currently have Datatable set up to upload images using the code snippet below: { label: "Images:", name: "files[].id", type: "uploadMany", display: function ( fileId, counter ) { re ...

Employing a "cross-domain" approach to serve as a login gateway for a different domain

I need to configure the domain: aaaa.com so that it can host a login form for the website located at domain: cccc.com. It's important to note that I have complete control over the server at cccc.com and have successfully set up CORS on that server. A ...

PHP and AJAX concurrent session issue causing difficulties specifically in Chrome browser

TL;DR. I'm encountering an issue in Chrome where different requests are seeing the same value while incrementing a session counter, despite it working fine in Firefox and Internet Explorer. I am attempting to hit a web page multiple times until I rec ...

Using the splice() method to remove an item from an array may cause unexpected results in React applications

Dynamic input fields are being created based on the number of objects in the state array. Each field is accompanied by a button to remove it, but there seems to be unexpected behavior when the button is clicked. A visual demonstration is provided below: ...

The instanceof operator does not recognize the value as an instance and is returning false, even though it

Is there a method to verify the current instance being used? This is what I am logging to the console: import { OrthographicCamera } from 'three'; // Later in the file: console.log(camera instanceof OrthographicCamera, camera); and the result ...