Ankur Aggarwal
Ankur Aggarwal

Reputation: 3101

How to check if user is refreshing the page or navigating to other page

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?

Upvotes: 1

Views: 4155

Answers (1)

Ahmet Can Güven
Ahmet Can Güven

Reputation: 5462

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
}

Upvotes: 4

Related Questions