Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React app detect if user refresh window or navigated away

I need to be able to detect if the user refreshed the window or navigated away (say google.com) and then return to the page so I can trigger an event.

I tried different onbeforeunload but it wasnt detecting it.

I tried, this and it wasnt working or triggering the console.log.

componentDidUpdate()
{
      window.addEventListener("onbeforeunload",function (){
        console.log('Page Refreshed')
     })
      
}

However, that doesnt even trigger the console.log message. I have also tried beforeunload and same results

any ideas why?


1 Answers

The best way to detect a page reload is to use window.performance.navigation which returns an object for the page containing two key-value pairs { redirectCount: 0 , type: 0 } shown below:

console.log(window.performance.navigation)

When the key type is equal to a value which is non-zero for example - type: 1 it depicts a page reload.

Note: Most probably the snippet won't work as expected. In that case you can switch to browser console and check it out yourself and don't forget to check the Preserve log checkbox under network tab of browser console.

To check if page is navigating away. Try unload event instead of onbeforeunload.

window.addEventListener("unload", function (e) {
  console.log('going away', e)
})

Lastly, in case of page load you can use lifecycle hooks. You can run some code as soon as the page loads in useEffect() of react-hooks in react or componentDidMount() if you're using class based syntax.

  1. useEffect()

     useEffect(() => {
      // Run as soon as page loads
      console.log('page loaded');
     });
    
  2. componentDidMount()

     componentDidMount() {
      // Run as soon as page loads
      console.log('page loaded'); 
     }
    
like image 129
Mohammad Basit Avatar answered Apr 02 '26 04:04

Mohammad Basit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!