diff --git a/.changeset/eleven-ads-destroy.md b/.changeset/eleven-ads-destroy.md new file mode 100644 index 000000000000..3af7595dd6bf --- /dev/null +++ b/.changeset/eleven-ads-destroy.md @@ -0,0 +1,5 @@ +--- +'@sveltejs/kit': patch +--- + +fix: correctly update `$page.url.hash` when navigating history diff --git a/packages/kit/src/runtime/client/client.js b/packages/kit/src/runtime/client/client.js index e9b660f2cd36..174b2413bd12 100644 --- a/packages/kit/src/runtime/client/client.js +++ b/packages/kit/src/runtime/client/client.js @@ -1668,10 +1668,12 @@ export function create_client(app, target) { if (event.state[INDEX_KEY] === current_history_index) return; const scroll = scroll_positions[event.state[INDEX_KEY]]; + const url = new URL(location.href); // if the only change is the hash, we don't need to do anything... if (current.url.href.split('#')[0] === location.href.split('#')[0]) { - // ...except handle scroll + // ...except update our internal URL tracking and handle scroll + update_url(url); scroll_positions[current_history_index] = scroll_state(); current_history_index = event.state[INDEX_KEY]; scrollTo(scroll.x, scroll.y); @@ -1681,7 +1683,7 @@ export function create_client(app, target) { const delta = event.state[INDEX_KEY] - current_history_index; await navigate({ - url: new URL(location.href), + url, scroll, keepfocus: false, redirect_chain: [], diff --git a/packages/kit/test/apps/basics/test/cross-platform/client.test.js b/packages/kit/test/apps/basics/test/cross-platform/client.test.js index 0e8f32c556fb..598c6e4c356e 100644 --- a/packages/kit/test/apps/basics/test/cross-platform/client.test.js +++ b/packages/kit/test/apps/basics/test/cross-platform/client.test.js @@ -641,6 +641,9 @@ test.describe('Routing', () => { await page.locator('[href="/routing/hashes/pagestore"]').click(); await expect(page.locator('#window-hash')).toHaveText('#target'); // hashchange doesn't fire for these await expect(page.locator('#page-url-hash')).toHaveText(''); + await page.goBack(); + expect(await page.textContent('#window-hash')).toBe('#target'); + expect(await page.textContent('#page-url-hash')).toBe('#target'); }); test('back button returns to previous route when previous route has been navigated to via hash anchor', async ({