Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use addEventListener to stop contextmenu event?

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.

like image 930
qiuyuntao Avatar asked Apr 18 '14 12:04

qiuyuntao


People also ask

How to prevent right-click menu?

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.

How to disable right-click menu in JavaScript?

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.

What is contextmenu event?

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.

How to disable right-click menu in browser?

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.


1 Answers

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

like image 122
Engineer Avatar answered Sep 28 '22 15:09

Engineer