Prevent Navigation When SaveBar is Active

Topic summary

A developer is working with Shopify’s Contextual SaveBar component and needs to prevent users from navigating away using browser back/forward buttons when unsaved changes exist.

Problem: The SaveBar component doesn’t natively block browser navigation, leaving users at risk of losing unsaved work.

Proposed Solution:

  • Implement the browser’s beforeunload event listener
  • Track unsaved changes using a boolean flag (hasUnsavedChanges)
  • Display a confirmation dialog when users attempt to navigate away
  • Use a useEffect hook to add/remove the event listener based on the unsaved changes state

Implementation Details:

  • Set e.preventDefault() and e.returnValue = '' to trigger the browser’s native confirmation dialog
  • Clean up the event listener when the component unmounts

The discussion remains open with one working solution provided but no confirmation of implementation or testing results.

Summarized with AI on October 29. AI used: claude-sonnet-4-5-20250929.

I am using the Contextual Save (SaveBar) component in Shopify. When the SaveBar is active or open, how can I prevent users from navigating to the next or previous page using the browser’s back and forward buttons?

Is there a recommended way to intercept these actions and prompt users to save their changes before leaving?

hi @DiwakarDahal

While Shopify’s ContextualSaveBar helps indicate unsaved changes, it doesn’t natively prevent browser navigation via the back or forward buttons. However, you can handle this with the browser’s beforeunload event to warn users before they navigate away, even when using the back/forward buttons.

Here’s a basic approach:

useEffect(() => {
  const handleBeforeUnload = (e) => {
    if (hasUnsavedChanges) {
      e.preventDefault();
      e.returnValue = ''; // Required for Chrome to show the confirmation dialog
    }
  };

  window.addEventListener('beforeunload', handleBeforeUnload);

  return () => {
    window.removeEventListener('beforeunload', handleBeforeUnload);
  };
}, [hasUnsavedChanges]);

This will prompt users when they try to leave the page — including with the browser’s back/forward buttons — if there are unsaved changes. Make sure hasUnsavedChanges is a boolean flag you set based on your form state.