Reputation: 554
I think this is impossible, but I'll ask our community of wizards, maybe someone has a trick.
A client is wants to trigger an event on my js injection platform when someone has reloaded the page more than twice. He refuses to either set a value on a cookie onbeforeonload or to have something on the server side that can count.
Anyone know of a way of counting page reloads on the client side?
Upvotes: 3
Views: 6340
Reputation: 349222
The performance.navigation
can be used to distinguish between navigation, history navigation and page reload.
Since you want to know whether the page was refreshed twice, some form of persistency is required because the browser does not keep track of the number of page reloads. For this purpose, the history API seems most sensible, because its state is tied to the page instance.
For example (demo showing number of reloads: https://robwu.nl/s/reloadCount.html):
// On load:
var state = history.state || {};
var reloadCount = state.reloadCount || 0;
if (performance.navigation.type === 1) { // Reload
state.reloadCount = ++reloadCount;
history.replaceState(state, null, document.URL);
} else if (reloadCount) {
delete state.reloadCount;
reloadCount = 0;
history.replaceState(state, null, document.URL);
}
if (reloadCount >= 2) {
// Now, do whatever you want...
alert('The page was reloaded more than twice!');
}
I've tested that the demo works in the following browsers:
If you need to support older browsers (that do not support the performance
API), then you could fall back to updating the history state with a timestamp upon unload, and check whether the timestamp (e.g. Date.now()
) in history.state
is close to the current time upon load.
Upvotes: 6