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
Mary-Kate OlsenOriginal
2024-12-20 11:54:10252browse

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

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!

Statement:
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