禁用右键单击嵌入元素内的 pdf

Ima*_*mad 1 html javascript pdf

我有一个embed元素,我在其中提供了pdf文件路径。我想防止它被下载。

<embed src="test.pdf" width="760" height="800" oncontextmenu="return false" />
Run Code Online (Sandbox Code Playgroud)

但是当我右键单击该 t 时,我可以选择保存和打印 pdf。我想阻止这些选项。

我试过

<script type="text/javascript">
    document.addEventListener("contextmenu", function (e) {
        e.preventDefault();
    }, false);
</script>
Run Code Online (Sandbox Code Playgroud)

但它禁用右键单击除 PDF 之外的整个页面。

Wen*_*lin 5

One simple and reliable solution, that is not affected by CORS or CSP, is to cover the embed with another element. I'm using an image here because you cannot embed pdfs on stack overflow.

.embed-cover {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  
  /* Just for demonstration, remove this part */
  opacity: 0.25;
  background-color: red;
}

.wrapper {
  position: relative;
  overflow: hidden;
}


/* Not Important*/
img {
  width: 300px
}
Run Code Online (Sandbox Code Playgroud)
<h3>Normal img/embed/object element</h3>
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a">

<hb/>

<h3>With cover</h3>
<div class="wrapper">
  <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a">
  <div class="embed-cover"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

The covering element 'catches' any click events and prevents them from reaching the underlying element (the image in this case)