From efccb59f2bd93cfdaf6e7a52e73c406efdda7fe0 Mon Sep 17 00:00:00 2001 From: Dimitris - Rafail Katsampas Date: Wed, 16 Jun 2021 14:27:51 +0300 Subject: [PATCH] fix: `popstate` listener was not removed on Router unmount --- Router.svelte | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/Router.svelte b/Router.svelte index aa6be6d..d13af44 100644 --- a/Router.svelte +++ b/Router.svelte @@ -454,18 +454,20 @@ let previousScrollState = null // Update history.scrollRestoration depending on restoreScrollState $: history.scrollRestoration = restoreScrollState ? 'manual' : 'auto' +const popStateChanged = (event) => { + // If this event was from our history.replaceState, event.state will contain + // our scroll history. Otherwise, event.state will be null (like on forward + // navigation) + if (event.state && event.state.__svelte_spa_router_scrollY) { + previousScrollState = event.state + } + else { + previousScrollState = null + } +} + if (restoreScrollState) { - window.addEventListener('popstate', (event) => { - // If this event was from our history.replaceState, event.state will contain - // our scroll history. Otherwise, event.state will be null (like on forward - // navigation) - if (event.state && event.state.__svelte_spa_router_scrollY) { - previousScrollState = event.state - } - else { - previousScrollState = null - } - }) + window.addEventListener('popstate', popStateChanged) afterUpdate(() => { // If this exists, then this is a back navigation: restore the scroll position @@ -588,5 +590,6 @@ const unsubscribeLoc = loc.subscribe(async (newLoc) => { onDestroy(() => { unsubscribeLoc() + window.removeEventListener('popstate', popStateChanged) })