I'm having trouble finding a solution for downloading files on iPhone Safari.

The code I shared is the current function in my application. It downloads the file correctly in Google Chrome, but it does not work in Safari.

How can I fix this so the file download works on Safari as well?

const downloadDocument = async (url) => { try { const response = await fetch(url) const blob = await response.blob() const blobUrl = window.URL.createObjectURL(blob) const link = document.createElement('a') link.href = blobUrl link.target = '_blank' link.download = url.split('/').pop() || 'document' document.body.appendChild(link) link.click() document.body.removeChild(link) setTimeout(() => window.URL.revokeObjectURL(blobUrl), 100) } catch (error) { console.error('Error downloading document.:', error) window.open(url, '_blank', 'noopener,noreferrer') } }

Abdulla Nilam's user avatar

Abdulla Nilam

40k18 gold badges86 silver badges115 bronze badges

Pedro Rufino's user avatar

New contributor

Pedro Rufino is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

4

As I know safari ignores a[download] for blob/object URLs.

The best is downloading via server headers. This works across all browsers.

If you control the server, return the file with:

Content-Disposition: attachment; filename="document.pdf"

Content-Type: application/pdf (correct mime shodul pass)

Optional: Content-Length

Some references

Alternative for 'download' attribute in Safari/iOS

Unable to download pdf blob url on Safari

Finally, do not blob it, just

const downloadDocument = (url) => { # must be triggered from a user action (tap/click) window.location.href = url; }; Or: const downloadDocument = (url) => { window.open(url, '_self'); # iOS behave better with _self };

Abdulla Nilam's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.