Skip to content

Commit

Permalink
fix: persist DOM state on beforeunload (#9345)
Browse files Browse the repository at this point in the history
fixes #9098
  • Loading branch information
Rich-Harris authored Mar 8, 2023
1 parent 1c32723 commit 0f863bb
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/gorgeous-dolphins-join.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

fix: persist DOM state on beforeunload
16 changes: 11 additions & 5 deletions packages/kit/src/runtime/client/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,14 @@ export function create_client(app, target) {
});
}

function persist_state() {
update_scroll_positions(current_history_index);
storage.set(SCROLL_KEY, scroll_positions);

capture_snapshot(current_history_index);
storage.set(SNAPSHOT_KEY, snapshots);
}

/**
* @param {string | URL} url
* @param {{ noScroll?: boolean; replaceState?: boolean; keepFocus?: boolean; state?: any; invalidateAll?: boolean }} opts
Expand Down Expand Up @@ -1447,6 +1455,8 @@ export function create_client(app, target) {
addEventListener('beforeunload', (e) => {
let should_block = false;

persist_state();

if (!navigating) {
// If we're navigating, beforeNavigate was already called. If we end up in here during navigation,
// it's due to an external or full-page-reload link, for which we don't want to call the hook again.
Expand Down Expand Up @@ -1476,11 +1486,7 @@ export function create_client(app, target) {

addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
update_scroll_positions(current_history_index);
storage.set(SCROLL_KEY, scroll_positions);

capture_snapshot(current_history_index);
storage.set(SNAPSHOT_KEY, snapshots);
persist_state();
}
});

Expand Down

0 comments on commit 0f863bb

Please sign in to comment.