Home > Back-end >  How to force PDF download in Firefox?
How to force PDF download in Firefox?

Time:03-17

I have following code for downloading PDF files from backend:

    const link = document.createElement('a')

    link.href = URL.createObjectURL(blob)

    link.setAttribute('target', '_blank')
    link.setAttribute('download', file_name)

    link.click()
    link.remove()
    setTimeout(() => window.URL.revokeObjectURL(url), 100)

It works in Chrome as expected, and I believe it worked in Firefox before, but now Firefox opens file in the same tab instead of downloading, ignoring target and download attributes.

CodePudding user response:

This is an example using fetch for an existing blob. You might want to skip first URL.createObjectURL and construct new Blob straight from the file.

Using this approach downloads pdf in the Firefox, but opens it in a new tab PDF viewer anyway.

const blobUrl = URL.createObjectURL(blob);
const filename = 'attachment.pdf';

fetch(blobUrl).then(res => res.arrayBuffer()).then(res => {
  const file = new Blob([res], {type: 'application/octet-stream'});
  const fileURL = URL.createObjectURL(file);
  const link = document.createElement('a');
  link.href = fileURL;
  link.download = filename;
  link.click();
  link.remove();
});

CodePudding user response:

This is expected behaviour for 98 and above. PDFs are set to open in Firefox by default.

If you change the mimetype you give the Blob to "application/octet-stream" or target the link whose href you assign to an iframe within your page, I think you'll get the previous behaviour back.

When the download attribute applies, it is treated the same way as a "Content-Disposition: attachment" header sent by the server. The Firefox developers think the user's preferences should win over what the server says - irrespective of whether the user has indicated they want the PDFs to open in an external app (Acrobat or w/e), automatically save to disk, or opening in Firefox.

Source: https://bugzilla.mozilla.org/show_bug.cgi?id=1756980

  • Related