1

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.

Ramesh G
  • 101
  • 1
  • 6

1 Answers1

1

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!

Aashish Peepra
  • 176
  • 2
  • 8
  • Hi Aashish, Thanks for the reply. The solution you provided isn't worked. Because, I need to restrict the refresh before the flow reaches lifecycle hooks. So I have put the event "onbeforeunload' in index.js file. Here the event calls in all actions like refresh, navigation, close etc... I need to detect the refresh action only which is triggered by refresh icon click. – Ramesh G Feb 04 '22 at 10:53
  • Why don't you store a timestamp when the "refresh button" is clicked, then in your index.js check if the timestamp is there, if it is there it means someone clicked on the refresh button, now once you have performed the refresh action, remove the timestamp from there. – Aashish Peepra Feb 04 '22 at 11:30
  • Aashish, storing the timestamp couldn't be helpful. Because, the event 'onbeforeunload'' will fire in both refresh and close actions. So the stored timestamp will show the same result for both the actions. And I want to restrict the refresh. And, it can be achieved only by the event 'onbeforeunload' when we return any or empty string. It will show one confirmation popup when we do reload, navigation and close actions. But I want this popup only on refresh. – Ramesh G Feb 04 '22 at 15:44
  • Do you want this popup only when they press on your refresh button or in general any refresh? – Aashish Peepra Feb 04 '22 at 15:51
  • Only on pressing the refresh icon of the browser. – Ramesh G Feb 05 '22 at 01:23