7

I read a lot about this topic and Safari seems to have issues with that (even filesaver.js). I still wonder whether any of you has an approach that makes it possible for a user to click a button and download a JSON file with a file name to his device.

There are a lot of relevant threads out there; and, Safari seems to have had issues with that in the past that have been resolved. But the current Safari versions still seem unable to do that. I am putting my last hope on you guys. An iOS update to the most recent version did not help.

Here is my approach, which works on Safari desktop:

    exportButton.addEventListener("click", () => {
      const appState = databaseConnector.getApplicationStateAsString();
      const blob = new Blob([appState], { type: "text/json" });
      const fileName = `backup_${
        new Date().toISOString().split("T")[0]
      }.json`;

      const tempElement = document.createElement("a");
      const url = URL.createObjectURL(blob);
      tempElement.href = url;
      tempElement.download = fileName;
      document.body.appendChild(tempElement);
      tempElement.click();

      setTimeout(function () {
        document.body.removeChild(tempElement);
        window.URL.revokeObjectURL(url);
      });
    });
greg-tumolo
  • 698
  • 1
  • 7
  • 30
codepleb
  • 10,086
  • 14
  • 69
  • 111
  • I have a website that uses something similar and it works, I see the file in the downloads folder. The claim that current safari version unable to download is not correct. In the worst case, post data back to server and reflect it back to client with proper Content-Type header and Content-Disposition: attachment; filename="filename.jpg" – ibrahim tanyalcin Jun 14 '20 at 21:58
  • Have you set the Content-Type to `application/octet-stream` and Content-Disposition to ` attachment; filename="filename.jpg" `? That should do it, it seems like Safari finally does allow arbitrary downloads. – Owen Versteeg Jun 18 '20 at 19:40

1 Answers1

1

Try the following code.

<!DOCTYPE html>
<title>Answer</title>
<a id=a download=answer.json href style=-webkit-appearance:button;color:black;text-decoration:none>Download</a>
<script>
a.href = "data:text/json;," + JSON.stringify({name: "answer"})
</script>
greg-tumolo
  • 698
  • 1
  • 7
  • 30