I want to prohibit the right mouse button. But I find that if I write this:
document.addEventListener('contextmenu', function(event) {
return false;
}, false);
It will not work, the event will still work.
But if I write it like this,
document.oncontextmenu = function() {
return false;
}
The right mouse button will not work.
I wish to know why I can't use addEventListener
to stop the event contextmenu
.
Press Windows + R hotkey to open Run Command. Type gpedit. msc and press Enter key. In the left side of Local Group Policy Editor, navigate to User Configuration > Administrative Templates > Start Menu and Taskbar, then double-click the “Remove access to the context menus for the taskbar” policy in the right side.
Inside the event listener, we prevent the default browser behavior by calling the ev. preventDefault() method. This will prevent the browser from displaying the right-click menu.
The contextmenu event fires when the user attempts to open a context menu. This event is typically triggered by clicking the right mouse button, or by pressing the context menu key.
Disable browser right-click for the whole page We can prevent this menu from appearing on right-click by latching onto the contextmenu event and using event. preventDefault() . If we add this event listener to the window object then we can prevent right-clicking on the whole page.
As stated in "Preventing the Browser's Default Action", the return of false
value is not enough for preventing default action. You need to call preventDefault()
method on Event
object:
document.addEventListener('contextmenu', function(event) {
event.preventDefault();
}, true);
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With