How To disable Right click and F12 key in a page using JavaScript
📅March 28, 2022
In this post, I’ll teach you how to prevent website content from being copied using JavaScript, which means I’ll show you how to deactivate mouse right click and keyboard F12 key.
- Detect URLs in text and create a link in JavaScript
- How to truncate a string in JavaScript
- Check whether a variable is number in JavaScript
- Calculate age using JavaScript
<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>
We may disable the right click using the preventDefault()
function in the contextmenu
event with the help of the above code. F12
, Ctrl + Shift + I
, Ctrl + Shift + J
, and Ctrl + U
are also disabled.
Instead of the contextmenu
event, You can also add the oncontextmenu
handler into the HTML body tag to disable the right click. Take a look at the code below.
<body oncontextmenu="return false;">
I hope you find this article helpful.
Thank you for reading. Happy Coding..!!