Home > Web Front-end > JS Tutorial > How Can I Detect Page Reloads and Refreshes in JavaScript?

How Can I Detect Page Reloads and Refreshes in JavaScript?

Susan Sarandon
Release: 2024-12-10 21:35:20
Original
872 people have browsed it

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template