In web development, we often need to distinguish whether a user has reloaded a page through a refresh operation. This may be done manually by the user (e.g., by pressing the F5 key or clicking the browser refresh button) or automatically by the browser reloading. Determining whether a page has been refreshed helps developers optimize the user experience. For example, if you are using vue and need to control permissions, you will need to determine whether to add a route based on the permissions of the logged in user after a refresh.
In this article, we will analyze in detail several common technical solutions for determining whether a page is refreshed or not, and discuss their application scenarios, advantages and disadvantages, as well as browser compatibility.
1. Utilization
is a persistent window property whose value is retained when the page is refreshed, or even when navigating to other pages via tabs, so it can be used to determine whether the page was reloaded via refresh.
code example
= function() {
if ( === 'isRefreshed' ) {
('The page was refreshed'); } else {
} else {
('Page loaded for the first time'); } else {
= 'isRefreshed';
}
}; }
Working Principle
- When first loaded, the
is the empty string, by setting it to
'isRefreshed'
to mark the status. - After refreshing the page
remains as
'isRefreshed'
, so you can tell that the page was loaded by refreshing.
vantage
- simple and easy to use: No reliance on external storage mechanisms or server-side logic.
-
Cross-page persistence: When navigating between pages, the
value remains, suitable for cross-page scenarios.
drawbacks
-
Security issues:
values are shared between pages and may be read by other pages.
-
manual cleaning: Manual removal may be required in some scenarios
, for example, when the page is closed.
compatibility
is a very old Web API with broad support in almost all browsers, including:
2. UtilizationsessionStorage
sessionStorage
is part of the Web Storage API, which maintains separate storage for each tab and whose data is emptied when the tab is closed. We can utilize thesessionStorage
to determine if the page has been refreshed:
= function() {
if (('isRefreshed')) {
('The page was refreshed'); } else {
} else {
('Page loaded for the first time'); } else {
}
('isRefreshed', true); }
}; }
Working Principle
- When the page is first loaded, the
sessionStorage
not includedisRefreshed
entry, so it can be determined that this is the first time it has been loaded. - By setting the
('isRefreshed', true);
, marking the page as loaded. - When the page is refreshed, the
sessionStorage
hit the nail on the headisRefreshed
The entry still exists, so a page refresh operation can be detected.
vantage
- Simple and independent of server-side logic.
- Only works on the current tab, suitable for single page or SPA (Single Page Application) scenarios.
drawbacks
- After closing a tab or browser window, the
sessionStorage
It will be emptied and the state cannot be saved.
compatibility
sessionStorage
is a widely supported API for the following browsers:
3. Utilization
API
browser-based The API provides detailed information about the page load, including whether the page was loaded by a refresh operation. This is accomplished by checking the
attribute can determine how the page is loaded.
= function() {
if ( === .TYPE_RELOAD) {
('The page was refreshed'); } else {
} else {
('Page loaded for the first time'); } else {
}
}; }
Properties Explained
-
.TYPE_RELOAD
: Indicates that the page is loaded by refreshing. - Other types (e.g.
TYPE_NAVIGATE
) indicates normal navigation.
vantage
- Directly provides an interface to determine whether the page is refreshed or not, which is more precise.
- There is no need to store the state manually.
drawbacks
- This API is being phased out and may not be supported by future browsers.
- Projects that are not suitable for long-term future maintenance should consider migrating to a newer API, such as the following
。
compatibility
API is supported in most browsers, but it is being phased out:
4. Utilizationbeforeunload
event
beforeunload
event is triggered before the user leaves the page, either by page refresh, closing or navigating to another page. In this event, we can set a flag bit to determine if the user left the current page by refreshing.
('beforeunload', function() {
('isRefreshed', 'true');
});
= function() {
if (('isRefreshed') === 'true') {
('The page was refreshed');
('isRefreshed'); // clear the flag after refreshing
} else {
('Page loaded for the first time'); }
}
};
Working Principle
- When the page is unloaded (including refreshed), a new page is added to the page via the
beforeunload
The event sets a flag bit. - When the page is reloaded, this flag bit determines whether the page was loaded by a refresh operation.
vantage
- Flexible enough to handle different types of page leaving operations.
-
localStorage
data is not cleared when the page is closed, so it can be used to determine refreshes across pages.
drawbacks
-
beforeunload
Events may behave inconsistently in some browsers (especially mobile). - If the user clears the browser cache or
localStorage
, then there is no way to properly judge it.
compatibility
beforeunload
Events are widely supported in most modern browsers, but may behave inconsistently in some mobile browsers:
5. Utilization
("navigation")
is a modern Web performance API for getting detailed information about page navigation. With this method, we can get an object that contains navigation information, and we can get it by checking the object'stype
attribute to determine whether the page was loaded by refresh or entered by some other means.
sample code (computing)
= function() {
const [navigationEntry] = ('navigation');
if (navigationEntry && === 'reload') {
('The page was refreshed');
} else {
('Loading the page for the first time');
}
};
Working Principle
-
('navigation')
Returns aPerformanceNavigationTiming
An array of objects containing details of the page navigation. - Through inspections
, you can determine the type of page load:
-
type === 'reload'
: The page is loaded by refreshing. -
type === 'navigate'
: The page is accessed through normal navigation. -
type === 'back_forward'
: The page is loaded via the browser's forward or back buttons. -
type === 'prerender'
: The page is loaded via pre-rendering (this state is usually uncommon).
-
vantage
-
modernity:
is a newer API that accurately distinguishes how pages are navigated in modern browsers.
- Detailed information: In addition to determining the page refresh, you can also get more data about the page loading performance, such as DNS resolution time, request time, etc., which helps to tune the page performance.
-
Stateless Management: no need to rely on
sessionStorage
、localStorage
and other external states, avoiding state synchronization problems.
drawbacks
- Browser compatibility: While most modern browsers support this API, Internet Explorer does not (not a problem anymore).
- Not applicable to multiple refreshes: A single judgment may be insufficient if tracking is required with multiple refreshes by the user.
Usage Scenarios
Ideal for scenarios where you just need to quickly determine if a page is loading on refresh and have further performance optimization needs. For modern web development, this is a more accurate solution that requires no additional storage or session management.
Example of monitoring page load performance
= function() {
const [navigationEntry] = ('navigation');
if (navigationEntry) {
(`Page Load Type: ${}`);
(`Page load time: ${ - } ms`);
}
};
This approach not only helps determine the type of page load, but also helps developers optimize page performance by providing more performance data to analyze page load bottlenecks.
compatibility
is a newer API that is widely supported in modern browsers, but not older ones:
summarize
Determining whether a page is refreshed is a common requirement, this article introduces five technical solutions. Each program has its specific applicable scenarios and advantages and disadvantages. Summarized below:
programmatic | vantage | drawbacks | Browser compatibility |
---|---|---|---|
|
Simple and easy to maintain state across pages | Security issues, manual cleanup required | Works with all modern browsers |
sessionStorage |
Simple, no reliance on complex logic | Empty when closing tabs | Supports modern browsers and some older browsers |
|
Provide page refresh judgment directly | APIs are being deprecated | Widely supported but gradually falling into disuse |
|
Precise determination of load type | Newer, not supported by older browsers | Only modern browsers are supported |
beforeunload |
Flexibility to handle multiple leave page actions | Not supported by some browsers, especially on mobile | Most modern browsers support |
Different solutions have their own advantages and disadvantages, and developers should choose flexibly according to the target user group of the application, performance requirements and browser support. If you need simple, cross-page refresh judgment, the is a good choice; and where a more precise and modern way of judging is needed, the
Provides greater flexibility.