Nooblet
Nooblet

Reputation: 41

Javascript to save textarea to file as UTF-8

I am using the following Javascript code to save a textarea to a text file on the user's machine. This is limited to our intranet and only IE is allowed so being limited to IE with limited security is not a big concern; however, I'm not able to use php. Therefore, I would like to stick to javascript and adjust the following script to force the charset to UTF-8. What I noticed when saving the file is that it would read correctly in notepad and notepad++ but when opening up in wordpad for example it was obvious that the UTF-16 was not satisfactory. Likewise, if I leave it to the save dialog and manually change the encoding to UTF-8 it saves all the text in the page rather than just the textarea. Also, if anyone knows how to change the default "save as type" to text .txt that would be awesome but not important.

    <script type="text/javascript">
function SaveContentsTXT(element) {     
    if (typeof element == "string")         
        element = document.getElementById(element);
        element3 = document.getElementsByName( 'TXTFILE' )[0];  
    if (element) {         
        if (document.execCommand) {                             
            var oWin = window.open("about:blank", "_blank");
            oWin.document.write((((element.value).replace(/ /g, '&nbsp;')).replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')).replace(/\n\r?/g, '<br />'));
            oWin.document.close();           
            var success = oWin.document.execCommand('SaveAs', true, element3.value);
            oWin.close();             
            if (!success)                 
                alert("Sorry, your browser does not support this feature or you canceled.");         
            }     
        } 
    } 
</script>

Upvotes: 2

Views: 4617

Answers (1)

Nooblet
Nooblet

Reputation: 41

oWin.document.charset="UTF-8";

The end result:

function SaveContentsTXT(element) {     
    if (typeof element == "string")         
        element = document.getElementById(element);
        txtitle = document.getElementsByName( 'TXTFILE' )[0];  
    if (element) {   
        if (document.execCommand) {                             
            var oWin = window.open("about:blank", "_blank");
            oWin.document.write((((element.value).replace(/ /g, '&nbsp;')).replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')).replace(/\n\r?/g, '<br />'));
            oWin.document.close(); 
            oWin.document.save="text";
            oWin.document.charset="UTF-8";
            var success = oWin.document.execCommand('SaveAs', true, txtitle.value);
            oWin.close();             
            if (!success)                 
                alert("Sorry, your browser does not support this feature or you canceled.");         
            }   
        } 
    } 

Upvotes: 2

Related Questions