Set the default save as name for a an or that uses a Blob [duplicate]

This answer is outdated.
The behavior described below did change since it was posted, and it may still change in the future.
Since this question has been asked elsewhere, with better responses, I invite you to read these instead: Can I set the filename of a PDF object displayed in Chrome?

I didn’t find, yet, for chrome’s default plugin.
I’ve got something that works for Firefox though, and which will default to download.pdf in chrome, for some odd reason…

By passing a dataURI in the form of

'data:application/pdf;headers=filename%3D' + FILE_NAME + ';base64,...'

Firefox accepts FILE_NAME as the name of your file, but chrome doesn’t…

A plnkr to show a better download.pdf in chrome, which doesn’t like nested iframes…

And an snippet which will only work in FF :

const FILE_NAME = 'myCoolFileName.pdf';
const file_header=";headers=filename%3D";

fetch('').then(r => r.blob())
  const f = new FileReader();
  f.onload = () => myPdfViewer.src = f.result.replace(';', file_header + encodeURIComponent(FILE_NAME) + ';');
<iframe id="myPdfViewer" width="500" height="500"></iframe>

But note that if it is really important to you, you could of course not rely on browser’s own plugins, and use e.g Mozilla’s PDF.js over which you’ll get an extended control.

Leave a Comment