Disable right click and F12 key using JavaScript
In this short article, we’ll explain to you how to disable right click using JavaScript. Sometimes you want to disable right-click to protect your own content or information from the user.
You need to just add the following script code in the <body>
section.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <script> // disable right click document.addEventListener('contextmenu', event => event.preventDefault()); document.onkeydown = function (e) { // disable F12 key if(e.keyCode == 123) { return false; } // disable I key if(e.ctrlKey && e.shiftKey && e.keyCode == 73){ return false; } // disable J key if(e.ctrlKey && e.shiftKey && e.keyCode == 74) { return false; } // disable U key if(e.ctrlKey && e.keyCode == 85) { return false; } } </script> |
With the help of the above code, we can disable the right click using preventDefault() method in contextmenu
event. Also disable the F12
, Ctrl + Shift + I
, Ctrl + Shift + J
and Ctrl + U
keys.
Instead of the contextmenu
event, You can also add the oncontextmenu
handler into the HTML body tag to disable the right click. Check out the following code.
1 | <body oncontextmenu="return false;"> |
That’s it for today.
Thank you for reading. Happy Coding..!!