I require the execution of a JavaScript function to occur after a web page has been refreshed, regardless of the method used (such as pressing F5, clicking the browser's refresh button, or re-entering the same URL). This action should only take place upon a page refresh, not during the initial page load.
Something along these lines:
window.onrefresh = function() { ... }; // of course, 'onrefresh' is not a real event
While I have come across some solutions on the web, none of them entirely meet my requirements:
Dirty Flag
This approach is quite straightforward - upon loading, check for a flag. If the flag does not exist, it signifies the first load, otherwise set the flag:
- Store the flag in either local storage or a cookie. The flag could be based on the current Date/Time. If the flag is not present on load, create it - indicating the first load. Otherwise, compare it with the current Date/Time after the refresh.
- Include the flag in the site's URL by using the '#' symbol ('#' will not alter site navigation). Similar to before, test for the presence of '#' at the end of the URL on load; if found, it indicates a "refresh" load, if not, this is the first load - thus add a '#' to the end of the URL.
performance.navigation
The window object features the property:
window.performance.navigation.type
, which can have 3 possible values:0 - Page loaded due to a link
1 - Page reloaded
2 - Page loaded due to the Back button
Nevertheless, this solution does not function as expected. The value returned is always "1", irrespective of whether it is the initial load or a refresh.