window.oncontextmenu
is already detecting mouse right click. What it does is disabling the default browser right click context menu for now, but you can add any additional code above it to trigger whenever right click event is performed.
window.oncontextmenu = function () {
console.log("right clicked");
return false;
}
You can try by running the code snippet and right clicking the empty space. Left clicking will not print the console.log.
EDIT: As mentioned in the comments, you could also use addEventListener
to listen to contextmenu
.
window.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
console.log("right clicked");
});