From 0f863bbc957ab2ed37b04ebd839fc864b945034d Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Wed, 8 Mar 2023 08:33:22 -0500 Subject: [PATCH] fix: persist DOM state on beforeunload (#9345) fixes #9098 --- .changeset/gorgeous-dolphins-join.md | 5 +++++ packages/kit/src/runtime/client/client.js | 16 +++++++++++----- 2 files changed, 16 insertions(+), 5 deletions(-) create mode 100644 .changeset/gorgeous-dolphins-join.md diff --git a/.changeset/gorgeous-dolphins-join.md b/.changeset/gorgeous-dolphins-join.md new file mode 100644 index 000000000000..0a42235fde3c --- /dev/null +++ b/.changeset/gorgeous-dolphins-join.md @@ -0,0 +1,5 @@ +--- +'@sveltejs/kit': patch +--- + +fix: persist DOM state on beforeunload diff --git a/packages/kit/src/runtime/client/client.js b/packages/kit/src/runtime/client/client.js index fabed659a94f..667844713503 100644 --- a/packages/kit/src/runtime/client/client.js +++ b/packages/kit/src/runtime/client/client.js @@ -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 @@ -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. @@ -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(); } });