Disable F5 Key (Button) And Browser Refresh Using JavaScript Or jQuery

Introduction

 
In this blog, I will share a trick to prevent the user refreshing the Browser, using Keyboard F5 function key by disabling 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 the keyboard F5 function key, stop its propagation by returning false inside the event handler.
 
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.
  1. <body onkeydown="return (event.keyCode != 116)">  
  2.     <h1>  
  3.         Click this page to set focus.  
  4.     </h1>  
  5. </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, false is returned to prevent the execution.=
  1. <body>  
  2. <script type = "text/javascript">  
  3.     window.onload = function () {  
  4.         document.onkeydown = function (e) {  
  5.             return (e.which || e.keyCode) != 116;  
  6.         };  
  7.     }  
  8. </script>  
  9.     <h1>  
  10.         Click this page to set focus.  
  11.     </h1>  
  12. </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, false is returned to prevent the execution.
  1. <body>  
  2. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  
  3. <script type="text/javascript">  
  4.     $(function () {  
  5.         $(document).keydown(function (e) {  
  6.             return (e.which || e.keyCode) != 116;  
  7.         });  
  8.     });  
  9. </script>  
  10. </body>