Files
sori.studio/plugins/bfcache-page-restore.client.js
zenn 3566144783 HTML 문서 페이지 뒤로가기 시 화면 잔상 문제 수정
- bfcache 복원 시 라우터 경로와 실제 URL 어긋남 감지해 새로고침하는 클라이언트 플러그인 추가
- HTML 문서 모드 페이지 진입 후 뒤로가기에서 주소는 홈이나 페이지가 남던 현상 해결
- v1.10.32

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-03 18:13:47 +09:00

39 lines
1.3 KiB
JavaScript

/**
* 뒤로가기/앞으로가기 캐시(bfcache) 복원 시 라우터 상태와 실제 URL이 어긋나면 새로고침한다.
*
* HTML 문서 모드 고정 페이지(`/pages/:slug`)로 SPA 내부 이동하면, 원문 HTML을 받기 위해
* `window.location.reload()`가 실행되면서 직전 문서(예: 홈)가 "라우터는 페이지 경로인데
* URL은 홈"인 어긋난 상태로 bfcache에 저장된다. 이 문서가 뒤로가기로 복원되면 주소는
* 홈이지만 화면은 페이지가 남는 문제가 생기므로, 어긋남을 감지해 새로고침으로 정상화한다.
*/
/**
* 경로 끝 슬래시·쿼리·해시를 제거해 비교용으로 정규화한다.
* @param {string} path - 원본 경로
* @returns {string} 정규화된 경로
*/
const normalizePath = (path) => {
const clean = String(path || '').split('?')[0].split('#')[0]
if (clean.length > 1 && clean.endsWith('/')) {
return clean.slice(0, -1)
}
return clean
}
export default defineNuxtPlugin(() => {
const router = useRouter()
window.addEventListener('pageshow', (event) => {
if (!event.persisted) {
return
}
const routePath = normalizePath(router.currentRoute.value.path)
const locationPath = normalizePath(window.location.pathname)
if (routePath !== locationPath) {
window.location.reload()
}
})
})