Ramesh G
Ramesh G

Reputation: 101

How to detect refresh action(by clicking refresh icon in browser)?

I want to restrict the page refresh only when we doing this by clicking the refresh icon at the top left side of the browser.

I have tried more available options like,

'beforeunload' event, which can fire on each time of unloading(refresh, navigation, close) the browser. Inside the event, I have tried 'window.performance.navigation.type' and window. performance.getEntrieaByType('navigation').map(nav=>nav.type) options. But both aren't giving the correct result. On each actions like "refresh", "navigation" and "close" getting the same result. Also sometimes getting different result. So I amn't trusting the options.

So can anyone help me to get the correct option to detect the refresh action done by browser refresh icon?

I am using react application.

Upvotes: 1

Views: 1928

Answers (1)

Aashish Peepra
Aashish Peepra

Reputation: 196

window.onbeforeunload = ()=>{
    localStorage.setItem("unload",Date.now());
}
useEffect(){
    let last_unload = localStorage.getItem('unload');
    let decided_time = 1000;
    if(last_unload){
        // means the user have closed the page 
        if(Date.now() - parseInt(last_unload,10) <= 1000)
        {
            // this is a refresh
            console.log('refresh handling code')
        }else{
            // It's a new session, means user came to page, closed the browser, now came back after a long time
        }
    }
}

Generally the answer from here

should work but because you are stating that window.performance is ambiguous in your case try something like this. Let me know if this helps!

Upvotes: 1

Related Questions