实际上,我想避免用户下载pdf。尝试通过添加事件侦听器禁用它。
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>
}
</>
);
最佳答案
如果您的最终目标是阻止用户下载pdf或任何与此相关的文件,那么您将会遇到问题。
一点点的恶意用户就知道如何获取为他们提供服务的任何文件。如果他们可以看到它,则可以下载它。 Javascript可能会阻止右键单击嵌入的内容,但不会阻止他们下载嵌入的内容。
无论如何,回答您的问题。据我所知,这里有两个直接选择:您似乎在试图防止用户右键单击图像以及PDF。专门嵌入无法正常工作。
那么在那时候为什么不只禁用整个页面的右键单击呢?
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>
如果您仍然希望用户能够右键单击,则对于嵌入的pdf,请用另一个元素代替它们,用户可以右键单击该元素。
有关如何执行此操作的绝佳示例,请参见此question。我们无法将pdfs嵌入Stack Overflow,因此他以图像为例,但是您应该明白这一点。
关于javascript - 如何禁用右键单击嵌入标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63521705/