Skip to content

Commit 37ea887

Browse files
committed
fix: improve back button navigation logic with visited paths tracking
1 parent 50326f1 commit 37ea887

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed

src/components/BackButton/index.tsx

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,36 @@
11
import { Button } from "@/components/ui/button";
22
import type { ReactNode } from "react";
33
import { MdArrowBack } from "react-icons/md";
4-
import { useEffect, useState } from "react";
4+
import { useEffect } from "react";
5+
6+
const VISITED_PATHS_KEY = "visited-paths";
57

68
export const BackButton = (props: {
79
href: string;
810
buttonLabel?: ReactNode;
911
contextLabel?: ReactNode;
1012
}) => {
11-
const [canGoBack, setCanGoBack] = useState(false);
12-
1313
useEffect(() => {
14-
const checkBackNavigation = () => {
15-
setCanGoBack(window.history.length > 1);
16-
};
17-
18-
checkBackNavigation();
19-
document.addEventListener("astro:page-load", checkBackNavigation);
14+
const currentPath = window.location.pathname;
15+
const storedPaths = sessionStorage.getItem(VISITED_PATHS_KEY);
16+
const visitedPaths = storedPaths ? JSON.parse(storedPaths) : [];
2017

21-
return () => {
22-
document.removeEventListener("astro:page-load", checkBackNavigation);
23-
};
18+
if (!visitedPaths.includes(currentPath)) {
19+
visitedPaths.push(currentPath);
20+
sessionStorage.setItem(VISITED_PATHS_KEY, JSON.stringify(visitedPaths));
21+
}
2422
}, []);
2523

2624
const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
27-
if (canGoBack) {
25+
const referrer = document.referrer;
26+
const hasReferrer = !!referrer && referrer.includes(window.location.host);
27+
const hasHistory = window.history.length > 1;
28+
29+
const storedPaths = sessionStorage.getItem(VISITED_PATHS_KEY);
30+
const visitedPaths = storedPaths ? JSON.parse(storedPaths) : [];
31+
const hasVisitedPaths = visitedPaths.length > 1;
32+
33+
if (hasHistory && (hasReferrer || hasVisitedPaths)) {
2834
e.preventDefault();
2935
window.history.back();
3036
}

0 commit comments

Comments
 (0)