1

Scenario: I want to set some variable in my localstorage whenever user leaves the page.

Using window.onbeforeunload I get the event that user is about to leave the page. But I want to set different variable value when user refreshes and different on page navigation

var someVar;
//when refresh someVar = 1;
//When user clicks on any link which is not the same page, someVar =2

Is this possible to detect if user is refreshing or about to leave page?

Ankur Aggarwal
  • 2,993
  • 5
  • 30
  • 56

1 Answers1

4

Based on your comment I am updating my answer. You can't detect navigation type on beforeunload event or with any other method because it is browser dependent. But I can provide you a way to detect back or refresh after the page loaded. I hope it will be useful.

Please check performance navigation

if (performance.navigation.type == PerformanceNavigation.TYPE_RELOAD){
 //Reload
}

if (performance.navigation.type == PerformanceNavigation.TYPE_BACK_FORWARD){
 //Back Button
}
Ahmet Can Güven
  • 5,392
  • 4
  • 38
  • 59
  • This is not working if I simply go to the url and hit enter. I know its not refresh but still the same url. Any way to detect this? Chrome is returning true in that case also but not working in firefox, safari on diret url hit – Ankur Aggarwal Jul 31 '17 at 12:43
  • Sorry but it is browser dependent issue. I don't know any solution for this case. – Ahmet Can Güven Jul 31 '17 at 12:56