I'm using React js. I need to detect page refresh
. When user hits refresh icon or press F5, I need to find out the event.
I tried with stackoverflow post by using javascript functions
I used javascript function beforeunload
still no luck.
onUnload(event) { alert('page Refreshed') } componentDidMount() { window.addEventListener("beforeunload", this.onUnload) } componentWillUnmount() { window.removeEventListener("beforeunload", this.onUnload) }
here I have full code on stackblitz
Use reload() Method to Refresh a Page in React Manually Browsers natively provide a window interface with a location object, including the reload() method. It's a fairly simple method, as you can see in the example below.
When the user refreshes the page it reset the CONTEXT or REDUX state and you have to set them manually again. So if they are not set or equal to the initial value which you have given then you can assume that the page is refreshed.
react-router-dom allows us to navigate through different pages on our app with/without refreshing the entire component. By default, BrowserRouter in react-router-dom will not refresh the entire page.
To maintain state after a page refresh in React, we can save the state in session storage. const Comp = () => { const [count, setCount] = useState(1); useEffect(() => { setCount(JSON. parse(window. sessionStorage.
Place this in the constructor:
if (window.performance) { if (performance.navigation.type == 1) { alert( "This page is reloaded" ); } else { alert( "This page is not reloaded"); } }
It will work, please see this example on stackblitz.
If you're using React Hook, UseEffect you can put the below changes in your component. It worked for me
useEffect(() => { window.addEventListener("beforeunload", alertUser); return () => { window.removeEventListener("beforeunload", alertUser); }; }, []); const alertUser = (e) => { e.preventDefault(); e.returnValue = ""; };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With