3

I have the following element that I would like to prevent from being downloaded by disabling the right click.

<iframe src={TEST + "#toolbar=0"} width="100%" height="800px" 
onMouseDown={(e)=>e.preventDefault()} onContextMenu={(e)=>e.preventDefault()}/> 

Unfortunately, when I right-click, it still brings up the context menu. Any idea why?

Kayla Song
  • 69
  • 1
  • 1
  • 6

2 Answers2

7

If you are using hooks then we can stop right click option in the following way

useEffect(() => {
        const handleContextmenu = e => {
            e.preventDefault()
        }
        document.addEventListener('contextmenu', handleContextmenu)
        return function cleanup() {
            document.removeEventListener('contextmenu', handleContextmenu)
        }
}, [ ])
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
5

Use the contextmenu event inside componentDidMount() method of your component.

For example:

componentDidMount() {
  document.addEventListener('contextmenu', (e) => {
    e.preventDefault();
  });
};

This will prevent the context menu to be shown.

j3ff
  • 5,719
  • 8
  • 38
  • 51
  • This still didn't work. I think iframe might not be detecting any clicks because having the onClick function in iframe to a console log doesn't print anything. Any idea how to fix this? – Kayla Song Apr 08 '20 at 22:30
  • Check this, you will find the answer: https://stackoverflow.com/questions/16792953/onclick-function-doesnt-fire-on-iframe – Mohammed-yassin HAMDAOUI Apr 15 '20 at 15:30