12

How to disable the context menu on long press when using device mode in Chrome ?

I mean this context menu:

enter image description here

I am asking this because I want to debug long press gestures for mobile devices and the context menu causes my react app to behave in a strange way:

when I try to reorder the list then "strange things start to happen": selected item starts to float all over the place (as can be seen from snapshot below). The Hello World is obscured by the selected item. Really strange.

enter image description here

3 Answers 3

26

My workaround is entering this code into the JS console when testing long press actions in device mode:

window.oncontextmenu = function() { return false; }
1
  • 1
    It will actually lead to the context menu open 'never', really, so... might not be exactly what many people would be satisfied with. Is a decent workaround, however. Nov 14, 2021 at 4:57
5

I have developed a slightly more "advanced" workaround that will still (most of the time) show the contextmenu on right-click while preventing it from showing on a simulated long-tap:

window.oncontextmenu = function() {
    if (event.button != 2 && !(event.clientX == event.clientY == 1)) {
        event.preventDefault();
    }
}
0

@marsk comment was right therefore based on previous answers I come up with another solution using PointerEvent.pointerType

window.oncontextmenu = function (event: any) {
  // eslint-disable-next-line no-console
  console.log(event); // prints [object PointerEvent]

  const pointerEvent = event as PointerEvent;
  // eslint-disable-next-line no-console
  console.log(`window.oncontextmenu: ${pointerEvent.pointerType}`);

  if (pointerEvent.pointerType === 'touch') {
    // context menu was triggerd by long press
    return false;
  }

  // just to show that pointerEvent.pointerType has another value 'mouse' aka right click
  if (pointerEvent.pointerType === 'mouse') {
    // context menu was triggered by right click
    return true;
  }

  // returning true will show a context menu for other cases
  return true;
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.