Search code examples
javascriptarraysvbscript

How to pass an array from VBScript to JavaScript?


I have a webpage where I am fetching the name of files in a Folder into an array using VBScript, then I am passing that array to JavaScript variable, so that I can display the names on the screen.

VBScript Code:

Function allFiles()
    Dim arr, arr2, oTargetFolder
    arr = array()

    set oFSO = CreateObject("Scripting.FileSystemObject")
    oTargetFolder = "C:\Users\msiddiq1\Documents\WSDLs"

    set objFolder = oFSO.GetFolder(oTargetFolder)

    set oFiles = objFolder.Files

    For Each files in oFiles
        ReDim Preserve arr(UBound(arr) + 1)
        arr(UBound(arr)) = files.Name       
    Next

    allFiles = arr
End Function

JS:

var folderFiles = allFiles();
alert(folderFiles.length); // alerts `undefined`

I can pass hardcoded values from vbscript to javascript, but not this array.

Please suggest.


Solution

  • You have to wrap the resulting array in a VBArray object and call toArray:

    var folderFiles = new VBArray(allFiles());
    var ff = folderFiles.toArray();
    alert(ff.length);
    

    or in one line:

    var folderFiles = (new VBArray(allFiles())).toArray();
    

    Note that VBScript is deprecated in IE11 edge mode, so it will be disappearing at some point.