Skip to content

Commit a8bdcf8

Browse files
authored
fix: correctly handle relative anchors when hash router is enabled (#13356)
fixes #13320 This PR enables relative hash links to be used with the hash router so that links such as #example get recognised as a link to the current page. We do this by assuming links that have a hash value starting with #/ links to a route while anything else is probably linking to an element with an id on the current page.
1 parent b764298 commit a8bdcf8

File tree

4 files changed

+23
-0
lines changed

4 files changed

+23
-0
lines changed

.changeset/forty-houses-collect.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@sveltejs/kit': patch
3+
---
4+
5+
fix: correctly handle relative anchors when using the hash router

packages/kit/src/runtime/client/utils.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,12 @@ export function get_link_info(a, base, uses_hash_router) {
130130

131131
try {
132132
url = new URL(a instanceof SVGAElement ? a.href.baseVal : a.href, document.baseURI);
133+
134+
// if the hash doesn't start with `#/` then it's probably linking to an id on the current page
135+
if (uses_hash_router && url.hash.match(/^#[^/]/)) {
136+
const route = location.hash.split('#')[1] || '/';
137+
url.hash = `#${route}${url.hash}`;
138+
}
133139
} catch {}
134140

135141
const target = a instanceof SVGAElement ? a.target.baseVal : a.target;
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
<a href="#test">go to #test</a>
2+
3+
<p id="test">#test</p>

packages/kit/test/apps/hash-based-routing/test/test.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,4 +89,13 @@ test.describe('hash based navigation', () => {
8989
url = new URL(page.url());
9090
expect(url.hash).toBe('#/reroute-b');
9191
});
92+
93+
test('relative anchor works', async ({ page }) => {
94+
await page.goto('/#/anchor');
95+
96+
await page.locator('a[href="#test"]').click();
97+
await expect(page.locator('#test')).toHaveText('#test');
98+
const url = new URL(page.url());
99+
expect(url.hash).toBe('#/anchor#test');
100+
});
92101
});

0 commit comments

Comments
 (0)