2

I have a requirement that asks the User "Are you sure you want to close the tab? In case you did not save, your answers will be lost" when closing the Lightning Application. Something like a popup that looks like this:

enter image description here

Does anyone know how to achieve this? I have researched about it and some are using the <script> tag but its not working. Any help would be greatly appreciated.

7

In Lightning, just go ahead and set it up as a normal event on the window object:

Controller

({
    doInit: function(component, event, helper) {
        helper.preventLeaving();
    },
    afterSave: function(component, event, helper) {
        helper.allowLeaving();
    }
})

Helper

({
    leaveHandler: function(event) {
            event.returnValue = "Are you sure you want to leave? All changes will be lost!";
    },
    preventLeaving: function() {
        window.addEventListener("beforeunload", this.leaveHandler);
    },
    allowLeaving: function() {
        window.removeEventListener("beforeunload", this.leaveHandler);
    }
})

This will cause the browser to prompt the user if they would like to leave or not. You should most likely set this only after the user has interacted with the form and has unsaved data.

  • Hi, thanks for your help! I tried this but upon loading the page, the popup is already showing. I need this popup to appear if and only if the user clicks on the close button of a browser's tab. What am I doing wrong? Thank you so much. – Max Nov 20 '17 at 6:30
  • @Max I don't know what you did wrong. This code works in my org. Be mindful of any extra () characters, perhaps. The code should be exactly as above. – sfdcfox Nov 20 '17 at 7:38
  • thank you so much, it is now working! i tried putting the helper.preventLeaving(); on a separate function while it is also in my doInit and it worked! not sure why but its working now. thank you! – Max Nov 21 '17 at 3:45
  • @Max, consider accepting the answer if it helped. – glls Mar 1 '18 at 21:34
0

In your lightning code add:

<ui:button label="Press Me" press="{!c.handleClick}"/>

In the controller add:

/*auraMethodController.js*/

({
    handleClick : function(cmp, event) {
        confirm("Do you Really want to save this Form");
    }
})
  • I do not need a button to trigger this functionality. What i need is that whenever a user clicks on the close button of a browser's tab, the popup should appear so it prevents the tab to be closed and ask the user first. Any idea on how I can achieve this? I tried putting a script tag on my lightning application but it doesn't work also :( – Max Nov 20 '17 at 6:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.