简体   繁体   中英

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>

  • an URL pointing to a PDF document: http://www.example.com

  • some javascript that will do iframe.src = pdfurl

  • a button that will trigger such 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

  • otherwise it will say "download 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

  • this won't allow me to display the correct button
  • onload does not fire if the file is being downloaded

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. 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

window.navigator.pdfViewerEnabled

Returns true if the user agent supports inline viewing of PDF files when navigating to them, or false otherwise. In the latter case, PDF files will be handled by external software.

MDN web docs article .

Browser compatibility table

支撑台

You could send a HEAD request to that resource and check what Content-Type and Content-Disposition values are being sent back. Based on these information you could determine whether a browser would display or download that resource.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM