Reputation: 801
I am trying to disable the context menu that pops up on right click for a specific div
. In the render I do
<div onContextMenu={(e) => {
console.log(e);
e.preventDefault();
e.stopPropagation();
return false
}}>
and it does print so I know its attached, but it still pops up in firefox ESR 60.8.0 even though its blocked in chrome.
Reason: I have a handsontable that I added a custom context menu to, and in firefox the native context menu renders on top of mine. Once I figure out how to block the context menu anywhere in firefox I will apply that to the handsontable in the custom renderer
EDIT: started bounty because none of the other hacks have worked for me and this is a pretty obscure case about a rare version of firefox
Upvotes: 1
Views: 2792
Reputation: 864
You need to cut the menu opening during the capture phase.
document.addEventListener("contextmenu", function(e) {
if(e.target.id === "YOUR ELEMENT ID") { // identify your element here. You can use e.target.id, or e.target.className, e.target.classList etc...
e.preventDefault();
e.stopPropagation();
}
}, true) // true means you are executing your function during capture phase
This code you can setup during componentDidMount or outside of your React code at all.
Upvotes: 6
Reputation: 801
A coworker helped me figure this out. It was a problem with my firefox setup that came preconfigured on my work computer. To fix it I had to go to about:config
url in firefox, and change the dom.event.contextmenu.enabled
value by double clicking. This changed it from “modified boolean false” to “default boolean true”. Expected behavior with e.preventDefault()
follows
Upvotes: 0
Reputation: 1785
The last resort could be binding the listener on the ref
of the element.
this.handsontableRef.addEventListener('contextmenu', (e)=> {
e.preventDefault();
console.log("open your context menu");
});
Tried this in Firefox, working for me. Share the exact code so that we can replicate on our end too.
Upvotes: 1
Reputation: 2937
I just tested this in firefox, ESR 60.8 for Mac and it works, could you double check if it does also for you.
Please double check that the event that you are calling preventDefault is the correct one, I had many times the error in which e is undefined.
Also I assumed that you are using react from the tag and the syntax of the post
class Example extends React.Component {
render() {
return (
<div className="red" onContextMenu={(e) => {
console.log(e);
e.preventDefault();
e.stopPropagation();
}}>hello click me</div>
);
}
}
ReactDOM.render(
<Example/>,
document.getElementById('root')
);
.red{
background: red;
height: 150px;
width: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>
Upvotes: 3