The editor of Downcodes brings you a detailed explanation of JavaScript monitoring page refresh events. Monitoring of page refresh events is crucial in web development. It can help developers perform some necessary operations when the page is refreshed or closed, such as saving user data, sending requests, etc. However, due to browser security restrictions, it is not easy to accurately distinguish between page refresh and close events. This article will take an in-depth look at several common methods and analyze their advantages and disadvantages to help you choose the most suitable option.
JavaScript can monitor page refresh events in several ways. The most common method is to use beforeunload and unload event listeners. However, it is important to note that it is technically difficult to only monitor page refreshes without monitoring closing events. Due to browser security restrictions, these two events are usually triggered at the same time. However, with some tricks, you can try to distinguish between these two events: for example, by setting a cookie or using sessionStorage to record the status, and check these statuses when the user loads the page again to determine whether the page is loaded due to a refresh or a close.
When the user attempts to refresh the page, some level of monitoring can be done through the beforeunload event.
window.addEventListener('beforeunload', function (e) {
//Set a warning message to display when refreshing
var confirmationMessage = 'Are you sure you want to refresh the page? ';
(e || window.event).returnValue = confirmationMessage;
return confirmationMessage;
});
This code will pop up a confirmation dialog box when the user refreshes the page. However, it also fires when the user attempts to close the page. Therefore, this is not a precise way to differentiate between refresh and shutdown.
The user's status information during the session can be recorded through sessionStorage. It is only valid within the current browser tab. When the tab is closed, the data stored in sessionStorage will be cleared.
//Executed when the page loads
window.onload = function() {
if (sessionStorage.getItem(is_reloaded)) {
console.log(the page was refreshed);
}
sessionStorage.setItem(is_reloaded, true);
};
window.addEventListener('beforeunload', function (e) {
if (!window.closed) {
sessionStorage.removeItem(is_reloaded);
}
});
In this example, we set the is_reloaded item in sessionStorage when the page loads. When the page refreshes, the item still exists, so we can tell whether the page has been refreshed by checking is_reloaded. This method also cannot accurately distinguish refresh and close, but combined with the analysis of user behavior patterns, it can provide a certain degree of distinction.
The Page Visibility API provides the ability to detect whether a page is visible to the user, and can also be used to indirectly determine user behavior.
document.addEventListener('visibilitychange', function() {
if (document.visibilityState === 'hidden') {
// The user has left the current page, possibly by closing or jumping
}
if (document.visibilityState === 'visible') {
// The page becomes visible, either by opening, refreshing, or switching back from another tab
}
});
Through this API, you can do some processing when the user leaves the page, and then make a judgment when the user returns to the page. However, this doesn't precisely monitor only refresh events.
You can set a cookie in JavaScript and give the cookie a short expiration time, check whether the cookie exists when the user refreshes, and judge it based on the timestamp:
//Set cookies
function setCookie(name, value, seconds) {
var expires = new Date(Date.now() + seconds * 1000);
document.cookie = name + = + value + ;expires= + expires.toUTCString();
}
// Get cookies
function getCookie(name) {
var keyValue = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
// Monitor refresh
window.addEventListener('load', function() {
var lastTime = getCookie('last_refresh_time');
var currentTime = Date.now();
if (lastTime && currentTime - parseInt(lastTime) < 1000) {
// If the difference between the two timestamps is less than 1 second, it is considered a refresh event
console.log(the page was refreshed);
}
setCookie('last_refresh_time', currentTime, 1);
});
By setting and checking the presence of the cookie and the difference from the current time, we may be able to infer whether a page has been refreshed or just opened. However, since cookies can span windows and tabs, this is still not a perfect solution.
1. How to monitor page refresh events through JavaScript?
You can monitor page refresh events through JavaScript to perform related operations. One way is to use beforeunload event.
window.addEventListener('beforeunload', function(event) { // Code executed before the page is refreshed // For example, sending requests, saving data, etc. });2. How to monitor only page refresh events but not page close events in JavaScript?
If you only want to monitor the page refresh event but not the page closing event, you can use the beforeunload and unload events in combination.
window.addEventListener('beforeunload', function(event) { // Code executed before the page is refreshed // For example, sending requests, saving data, etc. }); window.addEventListener('unload', function(event) { // Code executed when the page is closed // For example, cleaning up resources, saving exit time, etc. });In this way, when the user refreshes the page, the beforeunload event will be triggered, and when the user closes the page, both the beforeunload and unload events will be triggered.
3. How to monitor only refresh events of web pages in JavaScript while excluding monitoring of other navigation methods?
If you only want to monitor the refresh event of the web page, but not other navigation methods (such as clicking a link or clicking the forward/back button), you can use the beforeunload event in conjunction with the PerformanceNavigation interface.
window.addEventListener('beforeunload', function(event) { // Determine whether it is a web page refresh event if (performance.navigation.type === performance.navigation.TYPE_RELOAD) { // Code executed before the page is refreshed // For example Send requests, save data and other operations}});Use performance.navigation.type to determine the navigation type. If it is TYPE_RELOAD, it means that the page is triggered by a refresh operation. In this way, the corresponding code will be executed only in the web page refresh event.
I hope the above content can help you better understand the method of JavaScript page refresh event monitoring. The editor of Downcodes reminds you that in actual applications, you need to choose the appropriate method according to specific needs and handle compatibility.