user14289833
user14289833

Reputation:

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?

Upvotes: 3

Views: 12819

Answers (3)

Mohammad Basit
Mohammad Basit

Reputation: 575

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'); 
     }
    

Upvotes: 2

Anup
Anup

Reputation: 629

Try this

window.onbeforeunload = function(event) {
  console.log('Page Refreshed');
};

If you don't see the console you have to preserve the logs in the console.

Upvotes: 2

Nikko Khresna
Nikko Khresna

Reputation: 1009

The event name is not recognized, in addEventListener the event name should be "beforeunload".
"onbeforeonload" is window property, use it like "window.onbeforeunload = funcName".

If your console log didnt show, it might be cleared by browser, try persist the log, then see it console.log shows up

Upvotes: 1

Related Questions