How do I disable the context menu in Chrome on a Mac

I want a custom context menu and so need to be able to disable the context menu when the right mouse button is clicked.
I think that previously I did this by ‘preventDefault’ and ‘stopPropagation’ on the onContextMenu event. But that doesn’t work.
I first tried attaching the event listener to the body element and then to the document and finally the window.

body.addEventListener('contextmenu', function(ev){
    debugger;
    if(!ev.ctrlKey) {
        ev.preventDefault;
        ev.stopPropagation;
        alert("contextmenu blocked");
    }
}, false);

When the right mouse is clicked the alert is shown and when the alert is dismissed the chrome browser context menu appears.
The ‘if(!ev.ctrlKey)’ is so I can have the browser context menu by using the control right click.
My next thought was to add a mouse down event listener

body.addEventListener('mousedown', function(ev){
    debugger;
    if(!ev.ctrlKey) {
        ev.preventDefault;
        ev.stopPropagation;
        alert("mousedown blocked");
    }
}, false);

Now both alerts are shown followed by the context menu.
A left button click brings up the relevant alert and the normal action does not occur so the mouse down ev.preventDefault is working.

preventDefault and stopPropagation are functions, and need to be called as such.
ev.preventDefault();

1 Like

I’ve seen this applied which seems to work (in mac chrome):

document.addEventListener('contextmenu', event => event.preventDefault());

However are you sure this is a good idea?

I immediately leave sites that disable my right click.

2 Likes

Yup, me too, unless there’s very good reason (e.g. Google Docs).

In fact I hate sites that mess with any native browser functionality. E.g. Discourse overrides Ctrl+F to make you use its search functionality, which is almost never what I want to do.

3 Likes

Off-Topic

AFAIK, doing ctrl-f twice escapes the hijack and cedes to the browser.

3 Likes

It does indeed.
Took me a while to work that out :slight_smile:

1 Like

You are so correct. It is always these stupid things which trip you up.
Just for the record, this is an app which will be run on my desktop and laptop only.
I do not envision making it publicly available.
It has to be run on Chrome as Chrome has modal dialogs which are essential for it.

Do you mean support for the <dialog> element?

Yes it sports the dialog element.
Not only that but also modal dialogs.
And you can even cake another modal dialog from a modal dialog which returns back to the previous dialog when the new one is dismissed.
It is truely amazing.