最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Disable right click in React.js? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Apr 8, 2020 at 22:06 Kayla SongKayla Song 891 gold badge1 silver badge6 bronze badges 3
  • 1 Does this answer your question? Disable Right Click in React.JS – Zzirconium Commented Apr 8, 2020 at 22:08
  • No. I already saw it, but it doesn't work. – Kayla Song Commented Apr 8, 2020 at 22:15
  • ok maybe that's because you are trying to bind events from an iframe. Have a look at stackoverflow.com/a/30399256/2143734 – Zzirconium Commented Apr 8, 2020 at 22:19
Add a comment  | 

2 Answers 2

Reset to default 10

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)
        }
}, [ ])

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.

发布评论

评论列表(0)

  1. 暂无评论