Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in javascript how can I detect if a browser will display or download a pdf?

Tags:

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 :)

like image 701
Matteo Caprari Avatar asked May 18 '09 12:05

Matteo Caprari


People also ask

How can I download a PDF from a URL using JavaScript?

download = 'file. pdf'; link. dispatchEvent(new MouseEvent('click')); } var fileURL = "link/to/pdf"; var fileName = "test. pdf"; download(fileURL,fileName);


1 Answers

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.

like image 77
Jeff Ober Avatar answered Oct 14 '22 21:10

Jeff Ober