View Full Version : Disable context menu

26 Aug 2010, 10:32 AM
I'm trying to disable the context menu of a LayoutContainer when it's mask. I see a protected method, "disableContextMenu(boolean)", but it doesn't appear to work. Although it does call "event.preventDefault()" when set, it still calls Component.onRightClick(), which posts the dialog. I'm not sure of this is a bug, and the call to onRightClick should be within the if statement, or whether there is another way to disable a Component's context menu.


26 Aug 2010, 10:34 AM
You want to disable the native browser contextmenu or a contextmenu you set with component.setContextMenu?

26 Aug 2010, 10:58 AM
Both, actually. I have set a context menu of my own, and when the container it's attached to is masked, I don't want the right click event on that container to do anything. I don't want to post my own context menu, but I also don't want it to default back to posting the browser's context menu.

26 Aug 2010, 11:02 AM
Add a listener to the Events.ContextMenu event and cancel that. Than your own contextmenu wont be shown. disableContextMenu only disabled the native browser contextmenu.

26 Aug 2010, 11:54 AM
Perfect, thanks!

13 Jan 2011, 7:12 AM
I also want to disable a my own context menu on a treepanel.
I've tried a few variations eg. Listener<BaseEvent>, Listener<Component> and cancelBubble, stopEvent, setCancelled, etc.
So far no luck.
Please help.

Here is one example:

Listener<ComponentEvent> cancelContextMenuListener = new Listener<ComponentEvent>() {

public void handleEvent(ComponentEvent be) {
tree.addListener(Events.OnContextMenu, cancelContextMenuListener);

13 Jan 2011, 3:13 PM
cancleBubble is not cancelling an event, it just stops event bubbling. stopEvent will prevent the default action and also stop bubbling. This way the browser contextmenu should not appear.

13 Jan 2011, 11:36 PM
I have changed the code to use stopEvent(), but it's still not working.
It looks like it is only disabling the native context menu. It is not disabling my custom context menu. How can I achieve that?

14 Jan 2011, 12:44 AM
Disabling the custom context menu is not linked to any browser event. You need to "cancel" the ContextMenu event.

14 Jan 2011, 1:03 AM
Ok, but how?

14 Jan 2011, 3:38 AM
document.getElementById('yourElement').oncontextmenu = function(){return false};
// yourElement may be <body>, even <html> :-), any kind of <div>

14 Jan 2011, 3:41 AM
Thanks for the reply, but I'm using GXT. Looks like your example makes use of EXTJS.

14 Jan 2011, 4:05 AM
You need to listen to the Events.ContextMenu event and call setCanceled(true) on it.

14 Jan 2011, 6:31 AM
This is working thanks to you kind people.

Here is the code:

private Listener<ComponentEvent> cancelContextMenuListener = new Listener<ComponentEvent>() {

public void handleEvent(ComponentEvent e) {
tree.addListener(Events.ContextMenu, cancelContextMenuListener);