Block or detect downloads on iframes
P粉819533564
2023-08-31 21:35:46
<p>I ran into a problem that is very common to me, but I couldn't find the correct solution. </p>
<p>I have a document that is displayed via an iframe. There is a toolbar at the top where end users can download documents. Now I want to log information about the download (so I may need some events) or disable the download option. </p>
<p>I know I can disable the entire toolbar by adding #toolbar=0, but the end user can change it themselves and still download the documentation without logging it, so that's not a suitable solution for me. </p>
If you are not interested in
iframe
, you can use theembed
orobject
tag to prevent such toolbars from appearing.With iframes, if you want to disable download functionality, you may end up with something browser-specific, since different browsers will convert the iframe into different elements to actually render the PDF. If you know exactly which browser you are dealing with, you can try to unbind the listener from the download button, here is a solution I tested in Chrome and it seems to work:
Thanks to Ben D for his answer to this question about listener removal , if you want to go down the logging route, you can replace the cloneNode and replaceChild steps with addEventListener. I think this will still cause problems for users who are savvy/determined enough to be able to download the PDF (see additional information on this post: https://www.w3docs.com/snippets/html/how-to-embed-pdf -in-html.html), so depending on your end goal, I'd recommend rendering a static image preview of the PDF to guest users, while the full viewer may be limited to logged-in users.