Home >Web Front-end >JS Tutorial >How Can I Detect Page Reloads and Refreshes in JavaScript?
How to Detect Page Reloads or Refreshes in JavaScript
When working with web applications, it's often necessary to track user interactions such as page reloads or refreshes. Detecting these events can trigger specific actions or display relevant information.
Solution
To determine if a page has been reloaded or refreshed, you can leverage JavaScript's window.performance.navigation.type property. This property provides information about the type of navigation that occurred.
Using this property, you can write the following code to check for page reloads:
if (window.performance.navigation.type === performance.navigation.TYPE_RELOAD) { // Perform desired action, such as displaying an alert } else { // Perform an alternate action, indicating the page was not reloaded }
In the above code, the if statement checks whether the navigation type matches the TYPE_RELOAD value. If true, it implies that the page has been reloaded, triggering the desired action. If the condition is false, the page has not been reloaded.
Note:
Be aware that window.performance.navigation.type is deprecated and should not be used in new code. Refer to the answer provided by Ilya Zelenko for a recommended alternative.
The above is the detailed content of How Can I Detect Page Reloads and Refreshes in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!