skip to Main Content

I’m using signalr for real-time communication.
I want to do something when I leave the page or close the browser.
So I attached onclose event to the signalr.
But it’s event is also fired when I refresh the page.
Is there any way that can distinguish between leaving page or refreshing the page?
I’ve tried this code.

useEffect(() => {
    const handleBeforeUnload = (e) => {
      const { type } = window.performance.getEntriesByType("navigation")[0];
      if (type === "reload") {
        e.preventDefault();
        // Chrome requires the returnValue property to be set
        e.returnValue = "";
      } else e.returnValue = "You are about leave the page"; */
    };

    window.addEventListener("beforeunload", handleBeforeUnload);

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

But I think type is always "reload" and message is not the one I passed to e.returnValue.
it always shows this.

enter image description here

Please let me know if there is any solution.

2

Answers


  1. Yes, you can distinguish between leaving the page (closing the browser tab/window) and reloading the page using the beforeunload event and the unload event.

    window.addEventListener('beforeunload', function(event) {
     // Your code here
     // This code will run when the user is leaving the page
    });
    

    Here’s an example of how you can handle the unload event to detect when the page is being reloaded:

    window.addEventListener('unload', function(event) {
      // Your code here
      // This code will run when the page is being reloaded
    });
    
    Login or Signup to reply.
  2.   useEffect(() => {
       const handleBeforeUnload = (e) => {
        const { type } = window.performance.getEntriesByType("navigation")[0];
        if (type === "reload") {
          e.preventDefault();
          // Chrome requires the returnValue property to be set
          e.returnValue = "";
        } else {
          e.returnValue = "You are about to leave the page";
        }
      };
    
      const handleUnload = () => {
        // Perform your cleanup or additional actions here
      };
    
      window.addEventListener("beforeunload", handleBeforeUnload);
        window.addEventListener("unload", handleUnload);
    
          return () => {
          window.removeEventListener("beforeunload", handleBeforeUnload);
          window.removeEventListener("unload", handleUnload);
        };
        }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search