Disabling the context menu on long taps on Android

I would like to disable the context menu that appears after a long tap (touch and hold) on images in my web application. I've seen posts with different ideas how to do it, but none of them seem to work for me.

Is there a way to do this on Android via HTML/CSS/Javascript?


The context menu has its own event. You just need to catch it and stop it from propagating.

window.oncontextmenu = function(event) {
     event.preventDefault();
     event.stopPropagation();
     return false;
};

This should work on 1.6 or later (if I recall correctly). I don't believe there's a workaround for 1.5 or earlier.

<!DOCTYPE html>
<html>
<head>
  <script>
    function absorbEvent_(event) {
      var e = event || window.event;
      e.preventDefault && e.preventDefault();
      e.stopPropagation && e.stopPropagation();
      e.cancelBubble = true;
      e.returnValue = false;
      return false;
    }

    function preventLongPressMenu(node) {
      node.ontouchstart = absorbEvent_;
      node.ontouchmove = absorbEvent_;
      node.ontouchend = absorbEvent_;
      node.ontouchcancel = absorbEvent_;
    }

    function init() {
      preventLongPressMenu(document.getElementById('theimage'));
    }
  </script>
</head>
<body onload="init()">
  <img id="theimage" src="http://www.google.com/logos/arthurboyd2010-hp.jpg" width="400">
</body>
</html>

For me, absorbing all the events was not an option since I wanted to disable long press downloads while still allowing the user to zoom and pan on the image. I was able to solve this with css and html only by layering a "shield" div on top of the image like so:

<div class="img-container">
  <div class="shield"></div>
  <img src="path.jpg">
</div>

img {
    max-width: 100%;
}

.shield {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 1;
}

Hope this helps someone!