How can I catch the refresh button click (f5)? I have a task, that consist of several parts:
- when I make refresh (anyways of this action) - I must clear my localStorage;
- if change url or close page - localStorage must save he's condition.
I found several topict conneting with such problem. The main conclusion is to use window.onbeforeunload, but the same time, this event fires anytime (not only when refresh page, even when you change url/ctrl + shift + r/f5/ctrl + r etc....).
Do we have any chanсe to catch only refresh event? For example: some way to compare to url (current and which user want to open, if they are the same - it refresh)?
Asked
Active
Viewed 772 times
0

Andrew Ustimenko
- 31
- 1
- 4
-
http://stackoverflow.com/questions/18457797/how-to-know-whether-refresh-button-or-browser-back-button-is-clicked-in-firefox is it helpfull? – Унгамист Долматов Mar 23 '17 at 07:02
-
Possible duplicate of [detect back button click in browser](http://stackoverflow.com/questions/6359327/detect-back-button-click-in-browser) – CodeMonkey Mar 23 '17 at 07:08
-
no, i read this, but the sollution didnt help me. The main reason is that it includes a beforeunload event, witch catch all event. In my sace, i need only f5 or refresh button. – Andrew Ustimenko Mar 23 '17 at 07:44
1 Answers
0
What you want is not possible by that mean. Refresh action is not catchable. But you can achieve that behavior with this workaround:
if(self.window.name.indexOf("justAwordToNowisYourWindow")!=0){
self.window.name = "justAwordToNowisYourWindow";
alert( "first Load" );
}else{
alert( "reload" );
}
Also, as a good practice, use a timestamp to prevent weird behavior if multiple windows of your application are open:
var n = Date.now();
if(self.window.name.indexOf("justAwordToNowisYourWindow")!=0)
{
self.window.name = "justAwordToNowisYourWindow"+n;
alert( "first Load" );
}else{
alert( "reload" );
}

Christian Pastor Cruz
- 376
- 1
- 9
-
I was thinking about this but in my version i need to return some value from beforeunload event. How can i understand, we cant do this? Or its my misunderstanding of working beforeunload? If only i can catch the return value, all will be easier))) – Andrew Ustimenko Mar 23 '17 at 08:05
-
you can create a cookie in the before unload event with the name of your window, and the value you need to return. with more details on the business rules we can work around it. – Christian Pastor Cruz Mar 23 '17 at 08:33