Reputation: 22611
I want to stop the right mouse button on a HTML5 canvas bringing up the context menu, since it gets in the way of mouse-controlled games.
I've tried adding oncontextmenu="return false;"
to the canvas
tag attributes. This works when the canvas is using a 2D context, but not when it uses a WebGL context, in both Firefox and Chrome.
Is this somehow specified by the standard or is it two simultaneous browser bugs? Is there any way to work around this and block right clicks in a WebGL context?
Upvotes: 2
Views: 4220
Reputation: 8998
I use the following code when blocking a default browser action
element.onevent=function(e){
e.preventDefault();
return false;
}
This code makes absolutely sure that the default action will not occur
never use html attributes to prevent the default.
When I saw your question, I tried this under the same circumstances:
canvas.oncontextmenu=function(e){
e.preventDefault();
return false;
}
And it worked exactly as it should.
I hope this helps any future viewers of this question
Upvotes: 0
Reputation: 63862
Results may vary per browser so ensure this works on all targeted browsers. I only tried it in Chrome.
yourCanvas.addEventListener('contextmenu', function(e) {
if (e.button === 2) {
e.preventDefault();
return false;
}
}, false);
Working example: http://jsfiddle.net/cK9Rt/
(it will say "test" in the console but not make the context menu)
Upvotes: 7