I'm trying to save to file but getting error 'saveTextAsFile is not defined' see below
<script type='text/javascript' src='SaveTextAsFile.js'></script>
<textarea id="inputTextToSave" style="width:512px;height:256px"></textarea>
<table>
<tr>
<td>Filename to Save As:</td>
<td><input id="inputFileNameToSaveAs"></input></td>
<td><button onclick="saveTextAsFile()">Save Text to File</button></td>
</tr>
</table>
I have that function saveTextAsFile() in file SaveTextAsFile.js in the same directory as html:
function saveTextAsFile()
{
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
Add a slash to the beginning of your script tag src to make it absolute to your host, otherwise, if you are in an url say "localhost/foo/bar/", the
browser will try to load the file from "localhost/foo/bar/SaveTextAsFile.js", if you add the slash, it will try to load it from "localhost/SaveTextAsFile.js"
<script type='text/javascript' src='/SaveTextAsFile.js'></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With