javascriptiossafarimobile-safarifilesaver.js

How to download a JSON file with JavaScript on iOS Safari


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

Solution

  • 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>