skip to Main Content

Exit when the page is refreshed 🙁 help

Code:

useEffect(() => {
  const handleBeforeUnload = async (event) => {
    try {
      const cookies = new Cookies();
      cookies.remove("_token");
      const response = await axios.get("http://localhost:3001/logout", {
        withCredentials: true,
      });
    } catch (error) {
      console.error("Hata:", error);
    }
  };
  window.addEventListener("beforeunload", handleBeforeUnload);
  return () => {
    window.removeEventListener("beforeunload", handleBeforeUnload);
  };
}, []);

Only exit when the tab is closed

2

Answers


  1. beforeunload will call in both cases ( In tab close event and a page refresh event). but, you can use visibilitychange event here. You can add condition like this.

    Logic for check page is refreshed or not

    if (document.visibilityState !== "hidden") {
      console.log("Page is being refreshed");
      return;
    }
    

    Full code:

    useEffect(() => {
      const handleBeforeUnload = async (event) => {
        try {
          const cookies = new Cookies();
          cookies.remove("_token");
          // Check if the page is being refreshed or closed
          if (document.visibilityState !== "hidden") {
            console.log("Page is being refreshed");
            return;
          }
          // If not a refresh, proceed with the logout logic
          const response = await axios.get("http://localhost:3001/logout", {
            withCredentials: true,
          });
        } catch (error) {
          console.error("Error:", error);
        }
      };
    
      window.addEventListener("beforeunload", handleBeforeUnload);
    
      return () => {
        window.removeEventListener("beforeunload", handleBeforeUnload);
      };
    }, []);
    

    I have done this way in past, I don’t know this is the best way or not. Let me know, if you have any doubts.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search