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.
Please let me know if there is any solution.
2
Answers
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.
Here’s an example of how you can handle the unload event to detect when the page is being reloaded: