Search code examples
javascripteventsdom-eventskeypress

How to catch F5 key pressed when the mouse is outside my page?


How can I catch the F5 key press when the mouse is outside my page?

For example hovering on a scroll bar, or on an address bar, or on a menu etc.

Because in this case e.which, which usually contains 116 for F5, contains undefined

EDIT: After playing with Alexey Lebedev' jsfiddle I discovered that if the last user click was inside my page, I actually can catch F5.

However if the last user click was outside my page, the problem remains.

I would think the browser client area is not in focus, but then it should not get the keypress and should not be refreshed at all.


Solution

  • If the last user click is outside your page, for example in the address bar, it might still be a good idea to refresh the page on F5, but the page shouldn't be able to spy what URL you are typing, and thus shouldn't receive keyboard events.

    If your goal is to prevent losing unsaved data on refresh, you can show a confirmation on beforeunload.