Home >Web Front-end >JS Tutorial >How Can JavaScript Detect Page Reloads or Refreshes?
Question:
Can we determine if a user has refreshed or reloaded a page using JavaScript?
Explanation:
Often, it's useful to execute specific code or display an alert when a user refreshes or reloads a webpage.
Solution:
There are several ways to detect page reloads or refreshes, depending on the browser and its support for certain APIs.
Deprecated Method:
While deprecated, we can use the window.performance.navigation.type property on older browsers:
if (window.performance.navigation.type == window.performance.navigation.TYPE_RELOAD) { alert("Page has been refreshed"); }
Modern Method:
To utilize the Navigation Timing API in modern browsers, we can employ the following code:
if (performance.navigation.type == performance.navigation.TYPE_RELOAD) { alert("Page has been refreshed"); } else { alert("Page has not been refreshed"); }
The above is the detailed content of How Can JavaScript Detect Page Reloads or Refreshes?. For more information, please follow other related articles on the PHP Chinese website!