3

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);
}
2

For now, at least, you can't do this with LWC, as far as I can tell. Instead, use an Aura component and use lightning:unsavedChanges to block navigation away from your component. You can avoid rewriting your LWC by wrapping it in an Aura component to add the extra logic.

1
  • Thanks. Unfortunately unsavedChanges isn't supported in Community. Looks like we can't do what we want, for now. – David Cheng Aug 23 '20 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.