In this short article I will share a trick to prevent user refreshing the browser using Keyboard F5 function key by disabling the F5 function key using JavaScript or jQuery.
The idea is to determine the key code of the pressed key and if it is 116 i.e. ASCII key code of Keyboard F5 function key then stop its propagation by returning false inside the event handler.
Note: It is necessary to have focus on the page in order to handle the key down event. And hence it is recommended to click on the page and then try to refresh using F5 key.
 
Using BODY Tag
The very first method is the easiest one to implement. You need to define the onkeydown event handler within the body tag and simply return false if the pressed key is F5 function key i.e. ASCII key code 116.
<body onkeydown="return (event.keyCode != 116)">
    <h1>
        Click this page to set focus.
    </h1>
</body>
 
 
Using JavaScript
Inside the window onload event handler, I have attached the onkeydown event handler for the document where first the key code is determined and if it is 116 then false is returned to prevent the execution.
<body>
<script type = "text/javascript">
    window.onload = function () {
        document.onkeydown = function (e) {
            return (e.which || e.keyCode) != 116;
        };
    }
</script>
    <h1>
        Click this page to set focus.
    </h1>
</body>
 
 
Using jQuery
Inside the jQuery document load event handler, I have attached the onkeydown event handler for the document where first the key code is determined and if it is 116 then false is returned to prevent the execution.
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $(document).keydown(function (e) {
            return (e.which || e.keyCode) != 116;
        });
    });
</script>
</body>
 
 
Demo
 
Downloads