Use the history.block(blocker: Blocker) API to prevent users from navigating away from the current page. This is useful for warning users about unsaved changes.
When a navigation attempt is blocked, the provided callback is executed. The callback receives a transition object (tx) which allows you to:
- Access the target location via
tx.location.pathname. - Call
unblock() to remove the blocker. - Call
tx.retry() to re-attempt the navigation after the user has confirmed they wish to proceed.
You can use standard browser APIs like window.confirm or implement custom UI dialogs within the callback.
// Block navigation and register a callback that
// fires when a navigation attempt is blocked.
let unblock = history.block((tx) => {
// Navigation was blocked! Let's show a confirmation dialog
// so the user can decide if they actually want to navigate
// away and discard changes they've made in the current page.
let url = tx.location.pathname;
if (window.confirm(`Are you sure you want to go to ${url}?`)) {
// Unblock the navigation.
unblock();
// Retry the transition.
tx.retry();
}
});