最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to force PDF download in Firefox? - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Mar 16, 2022 at 8:59 Andrew RusinasAndrew Rusinas 1,0641 gold badge14 silver badges26 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 14

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/show_bug.cgi?id=1756980

Edit:
Firefox opening the file in the same tab and ignoring the target attribute, is a bug.

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

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();
});

发布评论

评论列表(0)

  1. 暂无评论