Home >Web Front-end >JS Tutorial >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:
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!