"Troubleshooting: The ExitApp Function in PhoneGap's navigator.app is not

I'm currently exploring Phonegap to create a new app, but for some reason the navigator.app.exitApp()? command doesn't seem to be functioning as expected.

  • This project marks my debut into the realm of hybrid apps.
  • My primary focus is on Android 5 as the target platform.
  • I am working on Windows utilizing Cordova CLI for development.

In order to trigger a JavaScript function, I am using the following code snippet:

<input type='button' onclick='exitApp();'/>

Here is the JavaScript function being called:

function exitApp() { navigator.app.exitApp(); }

Any suggestions or insights would be greatly appreciated!

Answer №1

Previously, using navigator.app.exitApp() was straightforward with a few challenges, but now Google and Apple have introduced significant obstacles for developers.

  1. Ensure that you wait for the deviceready event before calling the exit function. Consider displaying a splash screen or disabling the button until deviceready is triggered and the Cordova library is fully loaded.
  2. This is the current hurdle. It is now necessary to include a whitelist plugin and implement CSP for Android. The plugin is essential for enforcing CSP. One workaround is moving all JavaScript (including any on*=) and <style> (and style=) code into a separate file, except for using external online resources in relation to CSP.

Regarding #1,

Add this JavaScript code:

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

function onDeviceReady() {
    // alert("deviceready");
    document.getElementById('exitApp').addEventListener('click', function() {
        navigator.app.exitApp();
    });
}

Add this to your index.html:

<button id="exitApp">Exit</button>

For #2, a quick solution is:

Add the following lines to your config.xml

<plugin name="cordova-plugin-whitelist" source="npm" spec="1.1.0" />
<allow-navigation href="*" />
<allow-intent href="*" />
<access origin="*" /> <!-- Required for iOS9 -->

NOTE THAT YOUR APP IS NOW INSECURE. IT IS YOUR RESPONSIBILITY TO SECURE YOUR APP.
Include the following in your index.html

<meta http-equiv="Content-Security-Policy" 
         content="default-src *; 
                  style-src * 'self' 'unsafe-inline' 'unsafe-eval'; 
                  script-src * 'self' 'unsafe-inline' 'unsafe-eval';">

NOTE THAT YOUR APP IS NOW INSECURE. IT IS YOUR RESPONSIBILITY TO SECURE YOUR APP.
This guide on implementing the whitelist system will be beneficial once you are prepared to enhance the security of your app.
HOW TO: apply the Cordova/Phonegap the whitelist system

Answer №2

Implement the code snippet below:

function handleBackButton() {
    navigator.notification.confirm("Do you want to exit?", onConfirm, "Confirmation", ["Yes","No"]); 
}
function onConfirm(button) {
    if(button == 2){// If user selected No, do nothing
        return;
    } else {
        navigator.app.exitApp();// Quit the application
    }
}

You need to add the following plugin:

cordova plugin add org.apache.cordova.dialogs

Answer №3

To ensure your app responds correctly to the back button on your device, simply set up a listener within your device ready function.

onDeviceReady: function () {

    document.addEventListener('backbutton', function(e){
        e.preventDefault();
        //Add your dialog box code here!
    }, true);

    //Additional code can be added below
}

Answer №4

If you're looking for a simple way to exit your Ionic 3 application, the code snippet navigator.app.exitApp(); should do the trick perfectly. Happy coding!

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

Utilizing JSX within this.state results in it being displayed as plain text when rendered

Currently, I am dynamically rendering a list of elements and I need to insert other elements in front of them based on key-value pairs. I want to utilize <sup></sup> tags for these elements, but they are appearing as plain text rather than sup ...

Mastering Vue.js Component References

Here is the code snippet I am working with: <input type="text" @input="disableField($event.target)" :disabled="isFieldDisabled(????)" /> I am trying to pass the same value from $event.target to the isField ...

What is the reason for jQuery selector variables not functioning within namespaces?

I'm struggling to figure out why my code isn't working as intended. I'm trying to declare multiple variables, but something seems to be off. Can anyone help me spot the mistake? var message = (function ($) { var $modalBody = $( ...

When using xmlHttpRequest, the euro symbol may appear as a question mark

This dynamic script (taken from dynamicdrive) allows me to fill a div with the specified id dynamically: var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no) var loadedobjects="" var rootdomain="ht ...

Is Apache required for running NodeJs?

Recently, I set up a web project on my local machine following a tutorial. With the help of XAMPP, I was able to install MySQL and Apache to run my Node.JS backend. Now, I'm looking into hosting the project on an external server to make it accessible ...

Top-tier data preservation with Mongoose for MongoDB

While saving logs to MongoDB, it is important that the data saved is error-free. However, the main purpose of storing logs is to track down issues, so even in cases where there are errors or invalid data, it is crucial for the logs to be saved. There are ...

React 16 is able to efficiently render an array of numbers into table data using the map function

In my quest to display the most frequently used words, I have successfully fetched data from an API. I have set up the state for words and mapped the array in render(). However, instead of displaying the words along with their counts, I only see numbers ...

Leveraging the power of Dojo and Ajax to seamlessly integrate the html initialization process through the

I am dealing with a webpage that loads multiple sections via ajax. For example: <body> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js" djConfig="parseOnLoad: true, isDebug:true"></s ...

ReactJS: Component not updating after property change causing re-render failure

I've encountered a React problem and I'm having trouble pinpointing the issue. In the code snippet below, I've implemented an accordion component that should show or hide based on the value of a state variable called displayForm. The goal i ...

Unexpected behavior encountered with Angular module dependency injection

Having some difficulty managing dependencies for my node app. Here's the current structure: app.js var app = angular.module('myApp', ['myController', 'myFactory', 'rzModule', 'chart.js', 'myServ ...

Android JNI - Understanding the Ins and Outs

My current project involves developing a software that will function on both Windows CE and Android devices. Although I have not finalized any decisions yet, my initial plan is to utilize C++ coding for the majority of the program, allowing for reusabilit ...

Troubleshooting the Gravity Issue in Three.js and Physi.js

Attempting to rewrite a Physi.js example in my own style has been challenging. The gravity feature doesn't seem to be working properly, even though the render loop is functioning correctly and constantly firing. You can view what I have so far here: ...

Is it achievable to animate the offset with React Native Animated?

I am attempting to develop a dynamic drag and drop functionality, inspired by this example: My goal is to modify it so that when the user initiates the touch, the object moves upwards to prevent it from being obscured by their finger. I envision this move ...

Implement a jQuery loop that utilizes the fadeIn effect

Currently, I have a basic jQuery function in place to generate a small image slider: function gridhover() { $(".grid-item .slide-image").each(function(index) { $(this).delay(400*index).fadeIn(300); }); } $( ".grid-item" ).hover(function() ...

Merge arrays of objects if they share at least one common property

// The following is an array that needs to be transformed const data = [ { name: 'shanu', label: 'ak', value: 1, }, { name: 'shanu', label: 'pk&ap ...

What is the best way to loop through an array of documents returned by Mongoose using Mongoose?

Within my server built on node.js (express based), there is a function that retrieves all users. Here is the function: export async function findAllUser() { let users = await User.find({}).exec() return users } In my node.js application, I have two m ...

What is the correct method for sending data through a POST request to a PHP script?

UPDATE: I made a mistake while trying to debug the issue. Instead of correctly debugging the AJAX POST request, I was double-clicking the .php file in the Network tab and assuming it was sending the same headers as the actual ajax POST request. This led me ...

In Node.js, the module.exports function does not return anything

After creating a custom function called module.exports, const mongoose = require("mongoose"); const Loan = require("../models/loan_model"); function unpaidList() { Loan.aggregate([ { $group: { _id: "$ePaidunpaid", data: { $pus ...

Parsing dates using moment.js with strict format and specific locale

In a scenario, I face the challenge of dealing with dates in different locales and trying to parse them into RFC2822. However, there seems to be an issue where moment.js fails to parse certain dates correctly. For instance, the date "24 janv. 2022" does n ...

Ways to access a global JavaScript object in a separate .js file

How can I access an object that was initialized in my HTML document? This is what my HTML document looks like: ... <script type="text/javascript" id="controller">var controller = false;</script> ... <body onload="controller = ne ...