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.