Counting pages

I think this is not possible, but I will ask our wizard community if maybe someone has a trick.

Client wants to fire an event on my js injection platform when someone has reloaded the page more than twice. It refuses to either set a value in the onbeforeonload cookie or have anything server side that it can count.

Does anyone know a way to count client side page reloads?

+3


source to share


1 answer


performance.navigation

can be used to distinguish between navigation, history navigation and page reloading.

Since you want to know if the page has been refreshed twice, some form of persistent is required as the browser doesn't keep track of the number of page reloads. For this purpose, the history API seems to be the most sensible since its state is tied to the page instance.

For example (demonstration of the 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:

  • Safari 8+
  • Chrome 14+ (maybe earlier, I didn't bother testing 13-)
  • Opera 15+
  • Firefox 7+
  • Internet Explorer 9+

If you need support for older browsers (that don't support the API performance

), you can go back to updating the history state with a timestamp on unload and check if the timestamp (for example Date.now()

) was at history.state

close to the current time on load.

+4


source







All Articles