#17257·kit

Registering the `beforeunload` listener unconditionally

Author: teemingcCreated Sep 29, 2026Updated Sep 29, 2026
Labelsbreaking change

Both Google and Mozilla do not recommend registering the beforeunload listener unconditionally. We're currently doing this and everyone is affected regardless of whether they're using cancel from beforeNavigate to intercept the page from being closed (as hinted in this comment). We could:

1. Conditionally attach listener if beforeNavigate is used

This is the most backwards-compatible but still affects everyone who uses beforeNavigate.

2. Separate cancel and beforeNavigate APIs

If we can detect when cancel is used, we can conditionally attach the listener only when it's needed. For example:

javascript
import { beforeUnload } from '$app/navigation';

// beforeUnload also attaches the event listener and removes it when the component unmounts
beforeUnload(({ cancel }) => {
  cancel();
});