Skip to content

Commit

Permalink
fix: tolerant invalid hash (#399)
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu authored Oct 7, 2021
1 parent 4b76617 commit efc5e1b
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions src/client/app/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,14 @@ export function createRouter(
if (inBrowser) {
nextTick(() => {
if (targetLoc.hash && !scrollPosition) {
const target = document.querySelector(
decodeURIComponent(targetLoc.hash)
) as HTMLElement
let target: HTMLElement | null = null
try {
target = document.querySelector(
decodeURIComponent(targetLoc.hash)
) as HTMLElement
} catch (e) {
console.warn(e)
}
if (target) {
scrollTo(target, targetLoc.hash)
return
Expand Down Expand Up @@ -176,9 +181,16 @@ export function useRoute(): Route {
}

function scrollTo(el: HTMLElement, hash: string, smooth = false) {
const target = el.classList.contains('.header-anchor')
? el
: document.querySelector(decodeURIComponent(hash))
let target: Element | null = null

try {
target = el.classList.contains('.header-anchor')
? el
: document.querySelector(decodeURIComponent(hash))
} catch (e) {
console.warn(e)
}

if (target) {
const targetTop = (target as HTMLElement).offsetTop
// only smooth scroll if distance is smaller than screen height.
Expand Down

0 comments on commit efc5e1b

Please sign in to comment.