How to download and save a file from a WebView?

Does anybody here knows how to instruct “Cordova” and\or Android “WebView” to work with the “Save()” function below?

<!DOCTYPE html>

<a href='data:text/plain;charset=utf-8,This is a Test' download="Test.txt"> Save - Download </a>

<br><br>

<input type="button" value="Save - Download"  onclick='Save("User Data.txt", "Name: John" + "\r\n\r\n" + "Age: 18" + "\r\n\r\n" + "Country: USA")'>

<script>

function Save(filename, text) {    //_________________________ v1.0 ______________________________

var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);

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

element.click();

document.body.removeChild(element);

}

</script>

Hi Silvano,

See if adding target='_blank' works for you:

element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('target', '_blank');
element.setAttribute('download', filename);

or not specifying the filename, like so:

element.toggleAttribute('download', true);

Otherwise, what’s the device and OS version you are testing it on?

@Levon

  • true and ‘true’ (the file will be downloaded as “true.txt”)

  • _blank (the function works exactly the same way without it)

Just to make it clear, when opening the “.html” file directly from Android File Manager, the above “Save” function works perfectly well in “Android Google Chrome browser” and “Android Browser”.

The problem is not the Device\OS, the problem seems to be that Android\Cordova webviews only support downloads from http\https.

Web Apps use Android\Cordova webviews that’s probably why “Save” does not work.

Unfortunately, I can’t create Web Apps “.apk” files to test because my PC is not configured to do so. (Android Studio, Java, Cordova, etc …)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.