[SalesForce] Display alert on Lightning Component when browser is refreshed or closed

I would like to display an alert message on a Lightning Component, and proceed with commiting the changes on the form to the database on closing the browser window.

    <aura:component controller="Question" implements="flexipage:availableForAllPageTypes" access="global" >
    <!--<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>-->
    <ltng:require scripts="{!$Resource.unload}" afterScriptsLoaded="{!c.doInit}" />
    <aura:attribute name="recordId" type="String" default="0017F00000aMjJWQA0"/>
    <aura:attribute name="nonHoverList" type="String[]" default=""/>
    <aura:attribute name="hoverList" type="String[]" default=""/>
    <aura:attribute name="startWithNonHover" type="Boolean" default=""/>
    <aura:attribute name="noneChecked" type="Boolean" default="false"/>
    <aura:attribute name="options" type="List" default="[
        {'label': 'Ross', 'value': 'option1'},
        {'label': 'Rachel', 'value': 'option2'}
        ]"/>
    <aura:attribute name="value" type="List" default="option1"/>

    <div class="slds-box">
        <aura:iteration items="{!v.nonHoverList}" var="nonHov" indexVar="nonHovIndex">
            <lightning:formattedRichText value="{!nonHov}"/>
            <aura:iteration items="{!v.hoverList}" var="hov" indexVar="hovIndex">
                <aura:if isTrue="{!nonHovIndex == hovIndex}">
                    <p><button style="text-decoration:underline;" label="{!hov}" class="slds-button">{!hov}</button>
                        <lightning:helptext content="XYZ"/>
                        &nbsp;
                    </p>
                </aura:if>
            </aura:iteration>
        </aura:iteration>

        <lightning:checkboxGroup name="Checkbox Group"
                                 label="Select all that apply:"
                                 options="{! v.options }"
                                 value="{! v.value }"
                                 onchange="{! c.handleChange }"/>
    </div>
</aura:component>

unload.js


 var validNavigation = false;
    function endSession() {
      // Browser or broswer tab is closed
      // Do sth here ...
      alert("bye");
    }


      window.onbeforeunload = function() {
          if (!validNavigation) {
             endSession();
          }
      }

Best Answer

If you can wait till SPRING 19, this is a standard event provided by Salesforce.

Get Notified About Unsaved Changes

Notify the UI about unsaved changes in your component with the lightning:unsavedChanges Aura component. You can use lightning:unsavedChanges in standard and console navigation apps. You can then use a controller to save or discard the changes.

https://releasenotes.docs.salesforce.com/en-us/spring19/release-notes/rn_lc_unsaved_changes.htm?edition=&impact=

Related Topic