5

I am trying to implement unsaved changes functionality in the LWC component. Tried various approaches including using javascript & jquery and tried to fire it onbeforeunload but things don't seem to work. The same works on the HTML page but not as expected in LWC.

I tried using the below code in a util class:

const handleUnsavedChangesValidation = (hasModifiedData, updateClicked) => {

    console.log('>>>:::INN::hasModifiedData::', hasModifiedData);
    console.log('>>>:::INN::updateClicked::', updateClicked);

    var modified = hasModifiedData && !updateClicked ? true : false;     
    
    if(modified) {

        addEventListener("beforeunload", (evt) => {

            const unsaved_changes_warning = "Changes you made may not be saved.";
                                   
            evt.returnValue = unsaved_changes_warning;
            
            return unsaved_changes_warning;
        });
    }
    else
    {
          removeEventListener("beforeunload", () => {                 
            
            return true;
        });
    }
}

On any changes to the input field I tried calling the following method with these params : handleUnsavedChangesValidation(true, false)

On save button click I tried calling this handleUnsavedChangesValidation(true, true);

On trying the above, it works partially fine:

On load -> alert is not displayed (as expected)

On input updates -> If refresh is pressed (alert displays - expected)

On input updates -> If the tab is clicked is pressed (alert displays - expected)

On input updates -> If browser back button is clicked (it fails to display alert)

On input updates -> If update button is clicked (it still displays alert stating unsaved changes and then on click of Ok it saves. This is also not expected. Alert should not display here)

Post save -> On page refresh -> Now alert displays which is also not expected.

Once again if I click refresh it does not display an alert.

I am looped and tried finding many ways to handle this via static resource and other ways but could not do anything here. Tried to pass blank to the return value of unload yet no result. Tried passing return true as well as return false. Yet it seems to display an alert when we click on save.

Anyone knows any alternative or can someone please help me out here. I am looking for a solution that works for LWC implementation and not just html javascript.

Please help geeks. Any help is highly appreciated.

Thanks in advance, stay safe.

Regards, Rajesh

1
  • Could you share the LWC where you use this piece of code ? Commented Jul 10, 2024 at 15:37

1 Answer 1

0

Generally speaking this kind of event listener is usually attached to the window object. When you write it without anything it attach to the component (which doesn't produce the event) and you can also to attach it to document. Note that LWC framework is using what they call distortions which may modify some native behavior.

Looking at your code, it seems you attach several time the event listener. I would advise to attach once on connectedCallback and remove it on disconnectedCallback. And move the test of unsaved data to the event handler.

Like this:

unsavedChangeHandler = (event) => {
    if (this.hasUnsavedChange) {
        console.log('Changes you made may not be saved.')
    }
}

connectedCallback () {
    window.addEventListener('beforeunload', this.unsavedChangeHandler)
}

disconnectedCallback () {
    window.removeEventListener('beforeunload', this.unsavedChangeHandler)
}

Note that I am using an arrow function for the event handler to allow access to component properties.

That being said, LWC runs in a SPA (Single Page Application), which means you kind of never really leave a page which explains why you don't receive the event.

In the past, Salesforce had given an Aura component called lightning:unsavedChanges to handle such case. It appears to not have any equivalent in LWC.

Maybe you could wrap your component into an Aura component in order to make it work ... not ideal but at least it should work. As a workaround, I would suggest to make a visual change when the component is in "draft".

Finally there is a Salesforce idea to migrate the Aura in LWC, I strongly advise you to upvote if you want to see it one day :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.