Alex Rivera | Logout

How should an array be passed to a Javascript function from C#?

Asked 2011-07-08T04:18:29.250
12

I use a WebBrowser object from WPF and I'm calling some Javascript code in the page loaded in the browser like this:

myWebBrowser.InvokeScript("myJsFunc", new object[] { foo.Text, bar.ToArray<string>()});

Now, the js function is supposed to iterate over the elements of the second parameter (an array of strings) and do stuff accordingly. The only issue is that the parameter seems not to be passed as a js array.

For example,

alert(typeof theArray);

alerts "Unknown".

What is the proper way to pass an array as a parameter when invoking a js function from CSharp?

Edit
Report

2 Answers

5

It's not solving the issue itself but it solves the problem if you have only one array to pass: you can send an arbitrary number of parameters to a JavaScript function, and access them through the arguments special variable. It becomes analogous to a function accepting a variable number of arguments, with the same advantages and problems (for instance, you have to pass the array last, and as mentioned earlier you can only pass one).

Here's an example JavaScript function:

function foo()
{
    var stringArgs = [];
    for (var i = 0; i < arguments.length; i++)
        stringArgs.push(arguments[i]);

    // do stuff with stringArgs
}

And you'd call it from C# like this:

List<string> arguments = new List<string>();
arguments.Add("foo");
arguments.Add("bar");
webBrowser.InvokeScript("foo", arguments.ToArray());
answered 2011-07-08T04:38:55.183
3

You need to convert the array to a JS array first, something that looks like this:

["John", "Bob", "Sue"] // literal array

Two examples follow:

StringBuilder sb = new StringBuilder();
string[] stringArray = bar.ToArray<string>();

//Build the JS array.
sb.Append( "[");
for (int i = 0; i < stringArray.Length; i++)
{
    sb.AppendFormat( "'{0}', ", stringArray[i] );

}
sb.Append( "]");


// Now send the array to the JS function.
myWebBrowser.InvokeScript("myJsFunc", new object[] { foo.Text, sb.ToString() });

You may want to remove the trailing , as well. Don't forget to import the appropriate libraries for StringBuilder, which I think is System.Text.StringBuilder;

or use, example two:

string[] stringArray = bar.ToArray<string>();

// or simpler to use string join.
string jsArray = "[" + String.Join( ",", stringArray ) + "]";
//
myWebBrowser.InvokeScript("myJsFunc", new object[] { foo.Text, jsArray });
answered 2011-07-08T04:50:38.053

Your Answer