[英]in javascript how can I detect if a browser will display or download a pdf?
Say I have:说我有:
a webpage with an iframe: <iframe src="" style="display:none;"></iframe>
带有 iframe 的网页:
<iframe src="" style="display:none;"></iframe>
an URL pointing to a PDF document: http://www.example.com
指向 PDF 文档的 URL:
http://www.example.com
://www.example.com
some javascript that will do iframe.src = pdfurl
一些会做
iframe.src = pdfurl
javascript
a button that will trigger such javascript将触发此类 javascript 的按钮
if the browser is going to display the PDF inline, the button will say "view pdf" and when clicked will make the iframe visible如果浏览器要显示 PDF 内联,按钮会显示“查看 pdf”,单击时会使 iframe 可见
otherwise it will say "download pdf"否则它会说“下载pdf”
I found a way to detect whether the pdf has been loaded in the iframe: reading iframe.contentDocument.contentType
after onload
has fired, but我找到了一种检测 pdf 是否已加载到 iframe 中的方法:在
onload
触发后读取iframe.contentDocument.contentType
,但是
onload
does not fire if the file is being downloadedonload
不会触发Thanks :)谢谢 :)
To tell the client's browser to download a response as a file, set the Content-Disposition HTTP header to 'attachment' in your response.要告诉客户端的浏览器将响应下载为文件,请在响应中将 Content-Disposition HTTP 标头设置为“附件”。 This is no guarantee, but it's the proper method of telling the browser how to handle the content.
这不能保证,但它是告诉浏览器如何处理内容的正确方法。
在现代浏览器中,JavaScript 的全局 Navigator 对象有一个 plugins 属性,里面填充了一个 Plugins 数组,如果你能找到 Mimetype application/pdf 的 Plugin,你可以放心地假设浏览器会内联显示 pdf 文件,只要服务器当然,不会显式发送 content-disposition: 附件标头。
§ 8.9.1.6 PDF viewing support
§ 8.9.1.6 PDF 查看支持
window.navigator.pdfViewerEnabled
Returns
true
if the user agent supports inline viewing of PDF files when navigating to them, orfalse
otherwise.如果用户代理在导航到 PDF 文件时支持内联查看,则返回
true
,否则返回false
。 In the latter case, PDF files will be handled by external software.在后一种情况下,PDF 文件将由外部软件处理。
MDN web docs article . MDN 网络文档文章。
You could send a HEAD request to that resource and check what Content-Type
and Content-Disposition
values are being sent back.您可以向该资源发送HEAD 请求并检查正在发回的
Content-Type
和Content-Disposition
值。 Based on these information you could determine whether a browser would display or download that resource.根据这些信息,您可以确定浏览器是否会显示或下载该资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.