Disabling the context menu on long taps on Android

2019-01-03 23:07发布

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?

11条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-03 23:38

Through raw javascript there are no events that get called for the context menu. Perhaps in the Java world there is something... There are actually several issues regarding javascript events (such as focus not working right) in the Android webkit.

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-03 23:39

I've had a similar issue. I've tried couple of solution from this thread and another thread for safari on the same problem (Preventing default context menu on longpress / longclick in mobile Safari (iPad / iPhone)) . The bad part was that I couldn't use onTouchStart,onTouchEnd etc...

Only prevent the event from onContextMenu. Snippet from React 16.5.2. Tested in chrome only.

    <img {...props} onContextMenu={event => event.preventDefault()}
    onTouchStart={touchStart}
    onTouchEnd={touchEnd} />

Hope it helps somebody. Cheers!


查看更多
乱世女痞
4楼-- · 2019-01-03 23:40

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!

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-03 23:40
<a id="moo" href=''> </a>

<script type="text/javascript">
    var moo = document.getElementById('moo');

    function handler(event) {
        event = event || context_menu.event;

        if (event.stopPropagation)
            event.stopPropagation();

        event.cancelBubble = true;
        return false;
    }

    moo.innerHTML = 'right-click here';

    moo.onclick = handler;
    moo.onmousedown = handler;
    moo.onmouseup = handler;
</script>

Capture the onContextMenu event, and return false in the event handler.

You can also capture the click event and check which mouse button fired the event with event.button, in some browsers anyway.

查看更多
等我变得足够好
6楼-- · 2019-01-03 23:43

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;
};
查看更多
Fickle 薄情
7楼-- · 2019-01-03 23:44

That can be done using CSS:

img {
  pointer-events: none;
}
查看更多
登录 后发表回答