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