Hi…i provides another way to accessing javascript functions from c# here…
Call the InvokeScript method on the HtmlDocument.
C#
namespace System.Windows.Forms
{
public sealed class HtmlDocument
{
public object InvokeScript(string scriptName);
public object InvokeScript(string scriptName, object[ ] args);
}
}
For example, let’s assume that you have a System.Windows.Forms.WebBrowser object named webBrowser1 and you want to call a JavaScript function in the HTML page loaded in your WebBrowser called “showMe()”
JavaScript
function showMe()
{
…
}
C#
webBrowser1.Document.InvokeScript(“showMe”);
Adding parameters gets a bit more complicated, but not much. You can create an array of parameters as the API suggests and they will be passed in to the JavaScript function. However, there is an even simpler way to do it.
We will start by calling the following function
JavaScript
function showMe(x,y)
{
…
}
Let’s write a wrapper function in C# using the params keyword to let the compiler do the work for us. It will automatically convert any extra parameters into an array of objects, just like InvokeScript is expecting.
C#
private object MyInvokeScript(string name, params object[ ] args)
{
return webBrowser1.Document.InvokeScript(name, args);
}
…
int x = 50;
int y = 100;
MyInvokeScript(“showMe”,x, y);
Note that the InvokeScript will return the value that the JavaScript function returns. According to the documentation, if it is a native type such as a number or string, it will be returned as a string, but it can also return an object.
JavaScript
function createPoint(x, y)
{
// Assume I have a Point object
var p = new Point(x,y);
return p;
}
function setPoint (p)
{
// Do something useful with the Point p.
}
C#
object o = MyInvokeScript(“createPoint”, 50, 100);
It is possible to query information about the object using GetType and InvokeMember but I like that the object can be passed back into JavaScript
C#
MyInvokeScript(“setPoint”, o);
This is very powerful and, combined with the ability to call from JavaScript into C#, can allow you to embed many web applications that provide a JavaScript API into your C# application.
Cegonsoft