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

How Can JavaScript Detect Page Reloads or Refreshes?

Mary-Kate Olsen
Release: 2024-12-20 11:54:10
Original
251 people have browsed it

How Can JavaScript Detect Page Reloads or Refreshes?

Detecting Page Reloads or Refreshes in JavaScript

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

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

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!

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