Home > database >  javascript text file download not working on iPhone
javascript text file download not working on iPhone

Time:03-11

I'm trying to download a file which contains information captured through other means on the page. In this example those means have been replace with var listContacts = 'Here is some text to download in a txt'; to make the code more simple. It currently works on windows laptop and android phone.

This needs to work offline from an HTML file stored locally on the phone with no access to a server as that is the manner in which it will be used.

The iPhone we've tested on is running iOS 15 so the iOS <13 download bug which dominates search results shouldn't apply. Javascript is enabled in Safari. It doesn't work in Chrome either (where it does on Laptop and Android).

How can I get this to work on iPhone?

function download(text) {

  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,'   

encodeURIComponent(text));
  pom.setAttribute('download', 'Contacts.txt');

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);

}

var listContacts = 'Here is some text to download in a txt';
<button onclick="download(listContacts)">Download</button>

CodePudding user response:

Perhaps try this (sorry, also does not work in Chrome iOS but does in my Safari):

https://jsfiddle.net/mplungjan/xu9ra6dL/

test link: Click

(function() {
  var textFile = null,
    makeTextFile = function(text) {
      var data = new Blob([text], {
        type: 'text/plain'
      });

      // If we are replacing a previously generated file we need to
      // manually revoke the object URL to avoid memory leaks.
      if (textFile !== null) {
        window.URL.revokeObjectURL(textFile);
      }

      textFile = window.URL.createObjectURL(data);

      return textFile;
    };


  document.getElementById('textbox').addEventListener('input', function() {
    var link = document.getElementById('downloadlink');
    link.href = makeTextFile(textbox.value);
    link.style.display = 'block';
  }, false);
})();
<textarea id="textbox">Type something here</textarea>
<a download="info.txt" id="downloadlink" style="display: none">Download</a>

CodePudding user response:

Having spent an entire 3 days on this issue, I now know that safari won't allow you to run locally stored html files due to sandboxing and security. So my problem cannot be solved without jailbreaking my boss's expensive work iPhone which I do not intend to do.

The javascript works perfectly fine if it's hosted on the internet. It just won't work locally.

  • Related