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

How Can I Detect Page Refreshes and Reloads in JavaScript?

DDD
DDDOriginal
2024-12-14 09:38:151007browse

How Can I Detect Page Refreshes and Reloads in JavaScript?

Detecting Page Refreshes and Reloads in JavaScript

Detecting page refreshes or reloads is crucial for implementing functionality that responds to these browser actions. When a page is refreshed or reloaded, it reloads all of its content and resets the state of the application.

Checking for Page Refreshes

To check if a page has been refreshed, you can use the window.performance.navigation object. This object provides information about the navigation history of the page. In particular, you can use the following property:

performance.navigation.type

This property returns one of the following values:

  • 0 (TYPE_NAVIGATE): Page is loaded for the first time or navigated to from another URL
  • 1 (TYPE_RELOAD): Page is reloaded

Example:

The following code checks if the page has been refreshed and displays an alert if it has:

if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
  alert("Page has been refreshed!");
}

Note: The window.performance.navigation object is deprecated in modern browsers. For a more current approach, refer to the improved answer provided in the given response.

The above is the detailed content of How Can I Detect Page Refreshes and Reloads in JavaScript?. 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