News for hackers. Stuff that matters.

Approach to detect if end user press F5 or refresh button

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'; };

( 6 comments | on HN )
Re:Approach to detect if end user press F5 or refresh button by viraptor on Sunday November 22, 2015 @11:32PM (#10612880)
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?

Re:Approach to detect if end user press F5 or refresh button by _RPM on Sunday November 22, 2015 @11:48PM (#10612914)
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
Re:Approach to detect if end user press F5 or refresh button by cswangpeng on Monday November 23, 2015 @12:49AM (#10613089)
it is very important for single page application. In such application we need detect this from framework routing entry.
Re:Approach to detect if end user press F5 or refresh button by viraptor on Monday November 23, 2015 @04:10AM (#10613540)
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.
Re:Approach to detect if end user press F5 or refresh button by insoluble on Monday November 23, 2015 @02:02AM (#10613261)
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.
Re:Approach to detect if end user press F5 or refresh button by B_Howe on Monday November 23, 2015 @01:08AM (#10613139)
Why is it so important to refresh and what does it really do and its important functions?