SaveTextAsFile is undefined
I am trying to save a file but get the 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 a saveTextAsFile () function in the SaveTextAsFile.js file in the same directory as the 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();
}
+3
source to share
1 answer
Add a forward slash to the beginning of your script src tag to make it absolute for your host, otherwise if you specified in the URL "localhost/foo/bar/"
, the browser will try to download the file from "localhost/foo/bar/SaveTextAsFile.js"
, if you add a forward slash it will try to download it from"localhost/SaveTextAsFile.js"
<script type='text/javascript' src='/SaveTextAsFile.js'></script>
+1
source to share