Javascript将文本区域保存为UTF-8格式的文件

Javascript to save textarea to file as UTF-8

本文关键字:UTF-8 格式 文件 保存 文本 区域 Javascript      更新时间:2023-09-26

我正在使用以下Javascript代码将文本区域保存到用户机器上的文本文件中。这仅限于我们的intranet,并且只允许使用IE,因此仅限于安全性有限的IE并不是什么大问题;但是,我不能使用php。因此,我想坚持使用javascript,并调整以下脚本以强制字符集为UTF-8。我在保存文件时注意到,它在记事本和notepad++中可以正确读取,但当在例如写字板中打开时,很明显UTF-16并不令人满意。同样,如果我将其保留在保存对话框中,并手动将编码更改为UTF-8,它将保存页面中的所有文本,而不仅仅是文本区域。此外,如果有人知道如何将默认的"另存为类型"更改为text.txt,那将非常棒,但并不重要。

    <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>
oWin.document.charset="UTF-8";

最终结果:

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.");         
            }   
        } 
    }