Approach to detect if end user press F5 or refresh button

1 points by cswangpeng ↗ HN
It is important to detect if end user press F5 or refresh button is very important for popular single page application. Becasue we need at the time to redraw whole layout. Recently implement it in project with below code,

window.onbeforeunload = function () { sessionStorage.setItem('refresh', true); };

var isRefreshingPage = function () { var oldState = sessionStorage.getItem('refresh'); sessionStorage.setItem('refresh', false); return oldState == 'true'; };

7 comments

[ 3.1 ms ] story [ 19.0 ms ] thread
So how do you differentiate between an actual refresh and a "close tab, open website 2 days later"?

Also, what happens when someone has 2 tabs open with the app, closes one and tries to do some action in the other?

Edit: What I really want to ask is... why is this ever necessary?

It might be a good idea to add a timestamp to the local storage item, preferably make it a JSON string. Then decide a reasonable amount of time between a "refresh" to count it as an actual refresh
it is very important for single page application. In such application we need detect this from framework routing entry.
Why? When you load the page you either have existing dom tree or not. Client side already knows if this is the case without extra session variables.
Why is it so important to refresh and what does it really do and its important functions?
it is very important for single page application. In such application we need detect this from framework routing entry.
Why not just have a timestamp in the query string? This way, each tab could have a different such timestamp of when the page was first loaded in that tab. When the page is refreshed, a new request will be made with the old (previously requested) timestamp. This requires, of course, that you are storing previously used timestamps somewhere, such as in the cookie; this also requires (somewhat) that the buttons on the app are asynch and don't change the timestamp.