PhoneGap - navigator.app.exitApp() Not Working

Thomas Fifield picture Thomas Fifield · Feb 2, 2016 · Viewed 17.7k times · Source

I'm using Phonegap to make a small application but the navigator.app.exitApp()? isn't working at all.

  • This is my first hybrid app.
  • My target platform is Android 5
  • I'm developing on Windows with Cordova CLI.

I call a JavaScript function with this

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

JavaScript:

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

Ideas??

Answer

user3255670 picture user3255670 · Feb 3, 2016

it used to be that calling navigator.app.exitApp() had just a few stumbling blocks, but now both Google and Apple have thrown in major impediments for developers.

  1. Make sure your you wait for the deviceready events before you make the call to exit. You might consider putting up a splash screen, or greying out (disableing) the button or something until deviceready fires and the Cordova library is loaded.
  2. This is the *impediment*. You now need to add a whitelist plugin and for Android add CSP. The plugin is required for CSP. You can get around this by moving all Javascript (including any on*=) and <style> (and style=) into a separate file. EXCEPTION for CSP – using any online resources.

On #1,

Add this to your javascript:

// 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>

On #2, the quick answer is:

Add this 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 YOUR APP IS NOW INSECURE. IT IS UP TO YOU TO SECURE YOUR APP.
Add the following to 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 YOUR APP IS NOW INSECURE. IT IS UP TO YOU TO SECURE YOUR APP.
This whitelist worksheet should help when you are ready to be more secure.
HOW TO: apply the Cordova/Phonegap the whitelist system