JSFiddle - React, Tailwind, and code Playground
by Ico Dimchev
HTML
<form id="form" action="#">
<input id="input" type="text">
<button type="submit">download html</button>
</form>
JavaScript
var $form = document.querySelector('#form'),
$input = document.querySelector('#input'),
template = '<html><body> The text is: {{text}} </body></html>';
$form.addEventListener('submit', function (event) {
event.preventDefault();
var html = template.replace('{{text}}', $input.value);
downloadFile('janko.html', html);
})
function downloadFile(fileName, fileContent) {
let ghostLink = document.createElement('a');
if (navigator.msSaveBlob) {
navigator.msSaveBlob(new Blob([fileContent], {
type: 'text/html;encoding:utf-8'
}), fileName);
} else if (URL && 'download' in ghostLink) {
ghostLink.href = URL.createObjectURL(new Blob([fileContent], {
type: 'text/html;encoding:utf-8'
}));
ghostLink.setAttribute('download', fileName);
document.body.appendChild(ghostLink);
ghostLink.click();
document.body.removeChild(ghostLink);
} else {
location.href = 'data:application/octet-stream,' + encodeURIComponent(fileContent);
}
}