I have a custom Lightning Web Component that is placed on a page in a Customer Community. Community users use the LWC to enter and save data.
I would like the LWC to detect when the user tries to navigate to another page in the community (e.g. by clicking on a navigation menu tab, etc) so I can warn them about unsaved changes in the LWC.
I've read several posts about setting an event listener for beforeunload
like this one and this one.
However, my code only detects when the user tries to reload the browser page. It doesn't detect when the user clicks on a nav menu tab to go to a different community page.
Is there anyway for an LWC to detect a page navigation in Community?
Here's my LWC JS code snippet. Note I'm testing multiple approaches:
constructor() {
super();
window.addEventListener('beforeunload', this.beforeUnloadHandler.bind(this));
}
connectedCallback() {
window.addEventListener('beforeunload', this.beforeUnloadHandler.bind(this));
}
disconnectedCallback() {
window.addEventListener('beforeunload', this.beforeUnloadHandler.bind(this));
}
beforeUnloadHandler(event) {
console.log("in beforeUnloadHandler");
this.showToast(
"Success",
"in beforeUnloadHandler",
"success"
);
}
showToast(theTitle, theMessage, theVariant) {
const event = new ShowToastEvent({
title: theTitle,
message: theMessage,
variant: theVariant,
messageTemplate: "{0}",
messageTemplateData: [theMessage]
});
this.dispatchEvent(event);
}