#Warning on refresh (app directory)

4 messages · Page 1 of 1 (latest)

old shadow
#

Hey guys, whenever a user refreshes my Next.js app or tries to go to a different page/website, I want an popup message to appear warning them that they will lose their data/progress. I have tried using the beforeunload event listener with a useEffect hook but it didn't work. Here are some examples of what I've tried -

#1

useEffect(() => {
    window.beforeunload = function() {
        return true;
    };

    return () => {
        window.beforeunload = null;
    };
}, []);

#2

  useEffect(() => {
    const unloadCallback = (event) => {
      event.preventDefault();
      event.returnValue = "";
      return "";
    };

    window.addEventListener("beforeunload", unloadCallback);
    return () => window.removeEventListener("beforeunload", unloadCallback);
  }, []);

I am using the app directory. Anyone know how I can accomplish this? Thanks
EDIT - I get the popup when my inspect element is open

zealous solarBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

old shadow
#

I am getting this error

#

EDIT - SOLVED! If you haven't interacted with the website at all, there is nothing to lose when you refresh. only when I do shit does the popup come. That makes a lot of sense.