Skip to content

fix: correct hash routing behavior #13492

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/angry-peaches-beam.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

fix: correct navigation history with hash router and ensure load functions are rerun on user changes to URL hash
13 changes: 6 additions & 7 deletions packages/kit/src/runtime/client/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -2432,6 +2432,12 @@ function _start_router() {
if (!hash_navigating) {
const url = new URL(location.href);
update_url(url);

// if the user edits the hash via the browser URL bar, trigger a full-page
// reload to align with pathname router behavior
if (app.hash) {
location.reload();
}
}
}
});
Expand All @@ -2450,13 +2456,6 @@ function _start_router() {
'',
location.href
);
} else if (app.hash) {
// If the user edits the hash via the browser URL bar, it
// (surprisingly!) mutates `current.url`, allowing us to
// detect it and trigger a navigation
if (current.url.hash === location.hash) {
void navigate({ type: 'goto', url: decode_hash(current.url) });
}
}
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

<a href="/">/</a>
<a href="/#/a">/#/a</a>
<a href="/#/b">/#/b</a>
<a href="/#/a#b">/#/a#b</a>
<a href="/#/b/123">/#/b/123</a>
<a href="/#/b/456">/#/b/456</a>
Expand Down
16 changes: 16 additions & 0 deletions packages/kit/test/apps/hash-based-routing/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,20 @@ test.describe('hash based navigation', () => {
const url = new URL(page.url());
expect(url.hash).toBe('#/anchor#test');
});

test('navigation history works', async ({ page }) => {
await page.goto('/');

await page.locator('a[href="/#/a"]').click();
await page.waitForURL('/#/a');

await page.locator('a[href="/#/b"]').click();
await page.waitForURL('/#/b');

await page.goBack();
expect(page.locator('p')).toHaveText('a');

await page.goForward();
expect(page.locator('p')).toHaveText('b');
});
});
Loading