Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

saveTextAsFile is not defined

Tags:

javascript

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();
}
like image 411
irom Avatar asked Aug 07 '26 04:08

irom


1 Answers

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>
like image 188
taxicala Avatar answered Aug 09 '26 20:08

taxicala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!