I\'m creating an application in C# that hosts custom web pages for most of the GUI. As the host, I\'d like to provide a javascript API so that the embedded web pages can ac
You can use Reflection for that:
[ComVisible(true)]
public class ScriptObject
{
public void LongRunningProcess(string data, object callback)
{
string result = String.Empty;
// do work, call the callback
callback.GetType().InvokeMember(
name: "[DispID=0]",
invokeAttr: BindingFlags.Instance | BindingFlags.InvokeMethod,
binder: null,
target: callback,
args: new Object[] { result });
}
}
You could also try dynamic
approach. It'd be more elegant if it works, but I haven't verified it:
[ComVisible(true)]
public class ScriptObject
{
public void LongRunningProcess(string data, object callback)
{
string result = String.Empty;
// do work, call the callback
dynamic callbackFunc = callback;
callbackFunc(result);
}
}
[UPDATE] The dynamic
method indeed works great, and probably is the easiest way of calling back JavaScript from C#, when you have a JavaScript function object. Both Reflection and dynamic
allow to call an anonymous JavaScript function, as well. Example:
C#:
public void CallbackTest(object callback)
{
dynamic callbackFunc = callback;
callbackFunc("Hello!");
}
JavaScript:
window.external.CallbackTest(function(msg) { alert(msg) })
As @Frogmouth
noted here already you can pass callback function name to the LongRunningProcedure
:
function onComplete( result )
{
alert( result );
}
function start()
{
window.external.LongRunningProcess( 'data', 'onComplete' );
}
and when LongRunningProcedure
completes use .InvokeScript
as the following:
public void LongRunningProcess(string data, string callbackFunctionName)
{
// do work, call the callback
string codeStrig = string.Format("{0}('{1}')", callbackFunctionName, "{{ Your result value here}}");
webBrowser1.Document.InvokeScript("eval", new [] { codeStrig});
}