Awais Rafiq Chaudhry
Awais Rafiq Chaudhry

Reputation: 490

How to disable right click on embed tag?

Actually I want to refrain user from downloading the pdf. Tried disabling it by adding event listener.

useEffect(() => {
    let element = document.getElementById('pdf-div')

    if(element)
      element.addEventListener("contextmenu", (event: any) => event.preventDefault());
  }, [])
  return (
    <>
      {
        file.includes('.png') ? 
          <img src={require(`./../../mocks/${file}`)} alt="" className='pdf-document-img' /> :
          <object id={'pdf-div'} ref={ref} className='pdf-document' data={`${file}#toolbar=0`} type="application/pdf">
            <embed id={'pdf-div'} ref={ref} src={file} type="application/pdf" />
          </object>
      }
    </>
  );

Upvotes: 2

Views: 7420

Answers (1)

Ryan
Ryan

Reputation: 65

If your end goal is to prevent a user downloading a pdf, or any file for that matter, you're going to have issues.

Malicious users with a little know how can get any file you serve them. If they can see it, they can download it. Javascript may prevent right clicking on the embeded but won't prevent them from downloading it.

Anyway, to answer your question. From what I can see you have two immediate options here: It looks like you're trying to prevent users right-clicking images as well as PDFs. The embeded specifically isn't working.

So at that point why not just disable right-click entirely for the page?

var message="Function Disabled!";

function clickIE4(){
    if (event.button==2){
        alert(message);
        return false;
    }
}

function clickNS4(e){
    if (document.layers||document.getElementById&&!document.all){
        if (e.which==2||e.which==3){
            alert(message);
            return false;
        }
    }
}

if (document.layers){
    document.captureEvents(Event.MOUSEDOWN);
    document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
    document.onmousedown=clickIE4;
}

document.oncontextmenu=new Function("alert(message);return false")
<img src="https://www.w3schools.com/howto/img_woods_wide.jpg"/>

<h1>Test text</h1>
<p> Pure Javascript option to disable right-click on page entirely, rather than only on certain elements, etc </p>

If you'd still like users to be able to right click, then for embeded pdfs, cover them with another element that the user would right-click instead.

See this question for a great example of how to do this. We can't embed pdfs on Stack Overflow so he uses an image as an example, but you should get the idea.

Upvotes: 1

Related Questions