Skip to content

Commit 23541b4

Browse files
authored
feat(router): add replace option to useRouter for history management (#4788)
1 parent 875aa8b commit 23541b4

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

src/client/app/router.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ export interface Router {
2828
initialLoad?: boolean
2929
// Whether to smoothly scroll to the target position.
3030
smoothScroll?: boolean
31+
// Whether to replace the current history entry.
32+
replace?: boolean
3133
}
3234
) => Promise<void>
3335
/**
@@ -322,7 +324,7 @@ function normalizeHref(href: string): string {
322324

323325
async function changeRoute(
324326
href: string,
325-
{ smoothScroll = false, initialLoad = false } = {}
327+
{ smoothScroll = false, initialLoad = false, replace = false } = {}
326328
): Promise<boolean> {
327329
const loc = normalizeHref(location.href)
328330
const nextUrl = new URL(href, location.origin)
@@ -334,9 +336,13 @@ async function changeRoute(
334336
return false
335337
}
336338
} else {
337-
// save scroll position before changing URL
338-
history.replaceState({ scrollPosition: window.scrollY }, '')
339-
history.pushState({}, '', href)
339+
if (replace) {
340+
history.replaceState({}, '', href)
341+
} else {
342+
// save scroll position before changing URL
343+
history.replaceState({ scrollPosition: window.scrollY }, '')
344+
history.pushState({}, '', href)
345+
}
340346

341347
if (nextUrl.pathname === currentUrl.pathname) {
342348
// scroll between hash anchors on the same page, avoid duplicate entries

0 commit comments

Comments
 (0)