[Next.js] 브라우저 뒤로가기 막기

준이·2023년 2월 22일
0

Next.js + Typescript 환경에서 브라우저 뒤로가기를 눌렀을 때(모바일 포함)
뒤로가기를 막고 모달창을 띄우도록 했다.

지금 와서는 별 거 아닌 것 같지만 장장 이틀 정도
머리를 싸매고 구글링을 했다..

핵심 개념은 history.pushState와
window.addEventListener("popstate", ()=>{})입니다.

먼저 핵심 코드는 아래와 같습니다.

뒤로가기 이벤트를 실행시킬 페이지 내에 삽입

  useEffect(() => {
    history.pushState(null, "", location.href);
    window.addEventListener("popstate", () => {
      browserPreventEvent(onAlertModalOpen);
    });
    return () => {
      window.removeEventListener("popstate", () => {
        browserPreventEvent(onAlertModalOpen);
      });
    };
  }, []);

뒤로가기 버튼 클릭 시, 이벤트

export const browserPreventEvent = (event: () => void) => {
  history.pushState(null, "", location.href);
  event();
};

history.pushState

history.pushState(null, "", location.href)는 history에 Statck 쌓아줍니다.
window.addEventListener("popstate", ()=>{ 이벤트 })는 뒤로가기 실행 시, 이벤트를 뒤로 가지 않고 이벤트를 실행 시켜줍니다.

도움이 되셨길 바랍니다!

profile
25% Speciallist

0개의 댓글