v145 · Web APIs · Route Guard

Route guard with unsaved-changes check

Subscribe to navigation.transition, read the destination, and decide whether to block, allow, or redirect based on a fake "has unsaved changes" flag. The destination is now visible during the transition.

SPA scope. The Navigation API drives same-document navigation only. Try the route buttons below — each does a real navigate() call that we intercept.

state

no transition in flight

transition log

code

navigation.addEventListener('navigate', (e) => {
  const dest = navigation.transition?.destination;     // NEW
  if (dirty && dest?.url !== location.href) {
    if (!confirm('Lose unsaved changes?')) e.preventDefault();
  }
  if (dest?.url.endsWith('#admin') && !user.isAdmin) {
    e.preventDefault();
    navigation.navigate('#home'); // redirect
  }
});

see also