Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, if 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 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 so. I am putting my last hope into you guys. An iOS update to the most recent version did not help.

Here is my approach, that 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);
      });
    });
like image 254
codepleb Avatar asked Jun 14 '20 21:06

codepleb


People also ask

How do I download a JSON file from a website?

Using the Chrome browser, go to the url with the json, then right click, then 'Inspect'. That brings up the Chrome devtools ui. From there go to 'Sources' and you will see the json file in the list. Then right click and you will be able to click 'Save as'.

Why is PDF downloading as HTML safari?

That's usually caused by the web server the files are hosted on misidentifying the MIME type of the file (probably as text/html).

How do I view a JSON file on iPhone?

With JSON VIEWER, opening, searching and managing JSON files on your iPhone or iPad will no longer be a problem. To use it, touch the JSON file in any application, select "Open with .." And select JSON VIEWER.


1 Answers

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>
like image 98
greg-tumolo Avatar answered Sep 29 '22 00:09

greg-tumolo