avoid ActiveX to save a file

2019-08-06 15:48发布

问题:

There is a function that returns an array from a table:

 GetFilteredData: function()
    /*====================================================
        - returns an array containing filtered data:
        [rowindex,[value1,value2,value3...]]
    =====================================================*/
    {
        var row = this.tbl.rows;
        var filteredData = [];
        for(var i=0; i<this.validRowsIndex.length; i++)
        {
            var rowData, cellData;
            rowData = [this.validRowsIndex[i],[]];
            var cells = tf_Tag(row[this.validRowsIndex[i]],'td');
            for(var j=0; j<cells.length; j++)
            {
                var cell_data = tf_GetNodeText(cells[j]);
                rowData[1].push( cell_data );
            }
            filteredData.push(rowData);
        }
        return filteredData;
    },


I use this code to get the data to a CSV and save it straight to desktop:

<script language="JavaScript">
function WriteToFile() 
{
   var fso, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s = fso.OpenTextFile("exported.csv" , 2, 1, -2);
   var colvals = tf_table1.GetFilteredData(true);
   for (i=0; i<colvals.length; i++){
     s.write(colvals[i] + '\r\n');
 }
   s.Close();
}


It works fine, however IE security settings need to be set to Minimum (Internet Options -> Security). Is there any way to rewrite this code so that they would work on Medium (Default) Settings?
Thanks!

回答1:

Why does this require elevated privileges?

JavaScript cannot natively access the filesystem directly. The ActiveXObject you are using allows for JS to do that. It makes sense, right? We wouldn't want a website to have write access to our filesystem, because malicious users could possibly destroy data or put malicious programs on our computer. It'd be a drive-by download from hell. Only the most trusted sites should have that kind of access (and arguably, no website should be doing things like that).

How do I get around this?

I think the best thing for you to do is create the filtered CSV server-side, and allow the user to download it directly from your server. If the user is supposed to put it somewhere specific, you could write instructions that they read before downloading it. (maybe http://ux.stackexchange.com could suggest a nice way of doing this)