I have a LWC where the user can edit some records, but those changes are not persisted to the database right away. Instead, I would like to warn the user when they are about close the browser tab or change to another URL, or refresh the page... This works, more or less. The only thing I cannot manage is to capture a URL change within Salesforce. So my LWC is on the Quote page, but when the user clicks on the Opportunities Tab, the below code does not prevent that redirect to Opportunities and the Quote changes are lost.

async connectedCallback() {
    window.addEventListener("beforeunload", this.handleBeforeUnload.bind(this));

handleBeforeUnload(event) {
    if (!this.isQuoteSaved) {
        event.returnValue = "You have unsaved changes.";

Is there another listener I have to add? Why are SF redirects working differently than a redirect to another different URL?



1 Answer 1


Navigations within Lightning are done client-side, so it won't trigger the window's beforeunload event because the window isn't unloading. It should trigger if you try to refresh the page, though.

Aura has the lightning:unsavedChanges component that helps with what you want, but there's no LWC equivalent. You could try wrapping your LWC component in a Aura component that has lightning:unsavedChanges in it, but I've not tested to see if that works.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .