Search code examples
cordovauwpwinjscordova-win10

Cordova windows 10 add confirm message on software close button / alt+F4


How can I display a confirm message when user click on the software close button (X / Alt+F4) of a Cordova application running on windows 10 (desktop). I have tryed few things but nothing work:

//This only fire when clicking on the back arrow.
document.addEventListener("backbutton", onBackKeyDown.bind(this), false); 
function onBackKeyDown(e) {
    navigator.notification.alert('onBackKeyDown');
}

//This fire but to late and cannot cancel or display message
document.addEventListener( 'pause', onPause.bind( this ), false );
function onPause() {
    debugger;
    navigator.notification.alert('onPause');
};

//This is never fired
WinJS.Application.addEventListener("unload", unloadEv);
function unloadEv(ev) {
    navigator.notification.alert('unloadEv');
}

//This is never fired
window.onbeforeunload = onbeforeunload;
function onbeforeunload(evt) {
    navigator.notification.alert('onbeforeunload');
}

Thanks


Solution

  • Step : 1

    Close button is restricted Capabilities function to enable this

    Open package.windows10.appxmanifest on platform -> windows Folder.

    Step : 2

    In that xml package tag should like this

    <Package IgnorableNamespaces="uap mp rescap" xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10">

    In Capabilities tag add <rescap:Capability Name="confirmAppClose" />

    <Capabilities> <rescap:Capability Name="confirmAppClose" /> </Capabilities>

    Here xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapa and IgnorableNamespaces="rescap" is Enabling restricted Capabilities.

    Step : 3

    And add below javascript code on your js file and build

     Windows.UI.Core.Preview.SystemNavigationManagerPreview.getForCurrentView().oncloserequested = function (args) {
                args.detail[0].handled = true;
                var message = new Windows.UI.Popups.MessageDialog("Details is not Saved Do you want save or exit the application..?");
                message.commands.append(new Windows.UI.Popups.UICommand("Save", SaveHandler));
                message.commands.append(new Windows.UI.Popups.UICommand("Exit", UnsaveHandler));
                message.commands.append(new Windows.UI.Popups.UICommand("Cancel", CancelHandler));
                message.showAsync();
            }
            function SaveHandler(command) {
                    //save button
            }
            function CancelHandler(command){
                return false;
            }
            function UnsaveHandler(command) {
                window.close();
            }