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.

  • Is the issue resolved? I'm unable to make this work. can you please help me with the solution if its resolved for you.
    – Sukruti
    Mar 4, 2020 at 17:44

2 Answers 2


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


    doInit: function(component, event, helper) {
    afterSave: function(component, event, 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, 2017 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, 2017 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, 2017 at 3:45
  • @Max, consider accepting the answer if it helped.
    – glls
    Mar 1, 2018 at 21:34

In your lightning code add:

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

In the controller add:


    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, 2017 at 6:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .