If you have a website and want to restrict users from viewing your page source codes, copying page content or anything else, then this blog is written for you. In this blog, you'll learn how to easily prevent users from performing these actions by disabling mouse right-click and shortcut keys like ctrl + c, ctrl + x, ctrl + u, and ctrl + shift + i using vanilla JavaScript.
To disable right-click and shortcut keys using vanilla JavaScript, follow the steps below as per your requirement. If you don't have a website and want to test how these codes prevent users from doing such actions, you can create an index.html file and paste the given source codes into your file.
Copy the Code and Paste before </body>
JS
const disabledKeys = ["c", "C", "x", "J", "u", "I"]; // keys that will be disabled
const showAlert = e => {
e.preventDefault(); // preventing its default behaviour
return alert("Sorry, you can't view or copy source codes this way!");
}
document.addEventListener("contextmenu", e => {
showAlert(e); // calling showAlert() function on mouse right click
});
document.addEventListener("keydown", e => {
// calling showAlert() function, if the pressed key matched to disabled keys
if((e.ctrlKey && disabledKeys.includes(e.key)) || e.key === "F12") {
showAlert(e);
}
});
Paste the given JavaScript codes into your website Page Post wherever you want.
JS
const disabledKeys = ["c", "C", "x", "J", "u", "I"]; // keys that will be disabled
const showAlert = e => {
e.preventDefault(); // preventing its default behaviour
return alert("Sorry, you can't view or copy source codes this way!");
}
document.addEventListener("contextmenu", e => {
showAlert(e); // calling showAlert() function on mouse right click
});
document.addEventListener("keydown", e => {
// calling showAlert() function, if the pressed key matched to disabled keys
if((e.ctrlKey && disabledKeys.includes(e.key)) || e.key === "F12") {
showAlert(e);
}
});
Conclusion
If you write blogs on your site, these controls will be beneficial to you. But note that blocking the right-click context menu will also prevent the user from accessing other features of the browser or browser extensions.