Browser back button does not show popup of leave permission in next js

74 views Asked by At

I'm encountering an issue with handling the browser back button in my Next application. I have a useEffect hook set up to listen for the beforeunload event, where I check if latestGeneratedImages is empty before allowing the user to leave the page. However, when I navigate away from the page using the browser's back button, the leave permission popup does not appear. It works fine on page reload and when closing the browser using the cross button.

Here's the relevant code:

useEffect(() => {
  const handleBeforeUnload = (event: BeforeUnloadEvent) => {
    if (latestGeneratedImages.length > 1) {
      event.preventDefault();

      event.returnValue = true;
    }
  };

  window.addEventListener('beforeunload', handleBeforeUnload);

  return () => {
    window.removeEventListener('beforeunload', handleBeforeUnload);
  };
}, [latestGeneratedImages]);
0

There are 0 answers