2010-11-26 28 views

回答

2

是的,只要你主持JS在webrowser控制。您可以使用ObjectForScripting和文档属性以及com可见对象。实际上情况正好相反,你可以从JavaScript调用c#方法。动态类型允许您传递并使用复杂对象,而无需使用反射Invoke/GetProperty等。

这是一个非常简单的示例。

[ComVisibleAttribute(true)] 
public class Ofs 
{ 
    public void MethodA(string msg) 
    { 
     MessageBox.Show(msg); // hello from js! 
    } 
} 

public class Form1 
{ 

    void Form1() 
    { 
    WebBrowser b = new WebBrowser(); 
    b.DocumentText = "<script>" 
     + "var a = [];" 
     + "a.foo = 'bar!'"; 
     + "var jsFunc=function(y){alert(y);}" 
     + "var jsFunc2=function(){return a;}" 
     + "window.external.MethodA('hello from js!');</script>"; 

    b.ObjectForScripting = new Ofs(); // we can call any public method in Ofs from js now... 
    b.Document.InvokeScript("jsFunc", new string[] { "hello!" }); // we can call the js function 
    dynamic a = (dynamic)b.Document.InvokeScript("jsFunc2"); // c#'a' is js'a' 
    string x = a.foo; 
    MessageBox.Show(x); // bar! 
    } 
} 
0

是的,它可以调用从C#Javascript代码,而不是通过使用动态类型。

相反,您可以利用JScript.Net的eval功能。

下面的文章有这样的基础:

http://odetocode.com/Code/80.aspx

+1

感谢您的链接,但我的问题是:是否有可能从C#调用JavaScript只是linke IronPython或IronRuby? – 2010-11-26 18:16:42