sveltejs / sveltejs/kit

Document when and how the beforeunload dialog is shown

Open
#11,487 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

documentation
Dominant language
JavaScript
Stars
20.8k
Forks
2.3k
Avg merge
1d 16h
Merged PRs (30d)
156

Description

Describe the problem
beforeNavigate((navigation) => {
  if (!confirm('Hello World')) navigation.cancel();
});

This code is sufficient to trigger the browser-generated dialog.

Leave site? Changes that you made may not be saved. — Google Chrome

This can be reproduced by:

  1. Calling the beforeNavigate in the root page component.
  2. Starting a development server and navigating to the / page.
  3. Interact with the page and then attempt to close the tab (window).

This can confuse users, since the provided "Hello World" message is not used.

Instead, the browser provided generic dialog is shown. (which is intended)

Describe the proposed solution

In the beforeNavigate documentation:


  1. State that if navigation.willUnload is true, custom alerts cannot be shown.
  2. State the reason why the browser default dialog is shown in the following usage.
beforeNavigate((navigation) => {
  if (!confirm('Hello World')) navigation.cancel();
});

  1. Provide a way to reproduce the browser default behavior - such as calling the preventDefault() method in the beforeunload event's object.
Alternatives considered

I wasn't able to create a docs PR because I was uncertain about the way this works.

Is is because

  • When the navigation.willUnload is true,
  • The beforeunload event handler is used with a preventDefault()?
addEventListener("beforeunload", (event) => {});
Importance

nice to have

Additional Information

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the beforeNavigate documentation at https://kit.svelte.dev/docs/modules#$app-navigation-beforenavigate and compare its behavior with the linked MDN beforeunload documentation. Verify why navigation.willUnload leads to the browser-generated dialog and document when custom alerts are not shown, including a reproduction using beforeunload.preventDefault().

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.