PhoneGap - navigator.app.exitApp()不工作

时间:2016-02-02 04:03:28

标签: javascript android cordova phonegap-cli

我正在使用Phonegap制作一个小应用程序,但navigator.app.exitApp()?根本不起作用。

  • 这是我的第一个混合应用程序。
  • 我的目标平台是Android 5
  • 我正在使用Cordova CLI开发Windows。

我用这个

调用一个JavaScript函数
<input type='button' onclick='exitApp();'/>

JavaScript:

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

想法?

4 个答案:

答案 0 :(得分:6)

@Thomas,
过去,调用navigator.app.exitApp()只有几个绊脚石,但现在谷歌和苹果都给开发者带来了重大障碍。

  1. 在拨打退出之前,请确保等待deviceready个事件。你可能会考虑设置一个启动画面,或者灰色(禁用)按钮或其他东西,直到deviceready触发并加载Cordova库。
  2. 这是*障碍*。您现在需要添加whitelist插件,并为Android添加CSP。该插件是CSP所必需的。您可以通过将所有Javascript(包括任何on*=)和<style>(以及style=)移动到单独的文件中来解决此问题。 CSP的例外 - 使用任何在线资源。
  3. 在#1上,

    将此添加到您的javascript:

    // Wait for PhoneGap to load
    document.addEventListener("deviceready", onDeviceReady, false);
    
    function onDeviceReady() {
        // alert("deviceready");
        document.getElementById('exitApp').addEventListener('click', function() {
            navigator.app.exitApp();
        });
    }
    

    将其添加到index.html:

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

    在#2上,快速回答是:

    将此添加到您的config.xml

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

    注意您的应用程序现在已不确定。由您来保护您的APP。
    将以下内容添加到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';">
    

    注意您的应用程序现在已不确定。由您来保护您的APP。
    当您准备好更安全时,此白名单工作表应该会有所帮助 HOW TO: apply the Cordova/Phonegap the whitelist system

答案 1 :(得分:2)

使用以下内容:

function backKeyDown() {
    navigator.notification.confirm("Are you sure you want to exit?", onConfirm, "Please Confirm", "Yes,No"); 
}
function onConfirm(button) {
    if(button==2){//If User selected No, then we just do nothing
        return;
    }else{
        navigator.app.exitApp();// Otherwise we quit the app.
    }
}

您必须安装以下插件:

cordova plugin install org.apache.cordova.dialogs

答案 2 :(得分:1)

您也可以在设备就绪回拨中添加一个监听器

onDeviceReady: function () {

    document.addEventListener('backbutton', function(e){
        e.preventDefault();
        //TODO: throw up your dialog here!
    }, true);

    //other stuff here
}

答案 3 :(得分:0)

只需在此行中的任何地方使用(Ionic 3即可正常工作)

navigator.app.exitApp();

仅此而已。享受您的编码...

相关问题