I know I could potentially use the Cordova File plugin, but that seems to have multiple, platform-specific quirks (such as different directory structures) due to its low-level nature.
Today I found this answer that shows how to open a desktop browser's Save Dialog for the user to select where they want to save blob data, but it was dart code so I converted the idea to plain JavaScript:
function onSaveButtonClick() {
var blob = new Blob(['abcd'], {type: 'text/plain'}),
blobUrl = window.URL.createObjectURL(blob),
a = document.createElement('a');
document.getElementsByTagName('body')[0].appendChild(a);
a.href = blobUrl;
a.download = "file.name";
a.click();
a.innerHTML = blobUrl;
window.setTimeout(function() {
window.URL.revokeObjectURL(blobUrl);
}, 1000);
}
(Also note that the download
attribute of the <a>
is not supported by IE, but Edge and in addition to that, IE seems to block the a.click()
call.)
In the code above, setting the innerHTML
is only for debugging purposes and for production use, you may want to set a.style.display = 'none'
to hide the anchor altogether. I am also aware that the revokeObjectURL
call in a timeout is a bit of a code smell, but it seems to work in desktop Chrome and Firefox.
Now the question is: How can I achieve the same in a Cordova app? I mean, letting the user choose the file save location via a stock Save As dialog so I don't have to add platform-specific code to my app? Running this code in a Cordova app on Android just displays the anchor but doesn't ask the user to save the file - even clicking the link (before or after the timeout) manually doesn't show it.
Update:
There is a related question here:
How to make Phonegap's (Cordova) File API work like File API in normal browser
The only answer requires the user to install a separate (though free) app and is therefore a no-go as I'd like my app to be self-contained.