JSFiddle - React, Tailwind, and code Playground
HTML
<button id="clickme">
DOWNLOAD
</button>
JavaScript
function myFunction() {
console.log('clicked')
downloadFile('./file.to.download', 'filename')
}
function downloadFile(sUrl, filename) {
//If in Chrome or Safari - download via virtual link click
if ( navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1;) {
console.log('is safari')
//Creating new link node.
var link = document.createElement('a');
link.href = sUrl;
if (link.download !== undefined) {
//Set HTML5 download attribute. This will prevent file from opening if supported.
var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
link.download = fileName;
}
//Dispatching click event.
if (document.createEvent) {
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
link.dispatchEvent(e);
return true;
}
}
// Force file download (whether supported by server).
var query = '?download';
window.open(sUrl + query, '_self');
}
$(document).ready(function() {
$('#clickme').click(myFunction)
});