1

Is it possible to call javascript from c# something like this?

ScriptRuntime py = Python.CreateRuntime();
dynamic random = py.UseFile("cal.js");
var result =random.Add(1,2);

cal.js


 function Add(a, b) {

        return (a + b);
    }

2 Answers 2

2

Yes, as long as you host the js in a webrowser control. You can use the ObjectForScripting and document properties for this along with a com visible object. Indeed the opposite is true as well, that is you can call c# methods from JavaScript. The type dynamic allow you to pass, and work with, complex objects without having to use reflection Invoke/GetProperty, etc.

Here is a really simple example.

[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!
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Yes it is possible to call Javascript code from C#, but not by using dynamic types.

Instead, you can leverage JScript.Net's eval functionality for this.

The following article has the basics of doing this:

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

2 Comments

As Chibacity said, you can't use the dynamic keyword with the current JScript engine, so it won't benefit from the new syntax. You can call JavaScript code using eval, however.
@santosh The answer to your question is: No. I have provided an alternative to achieving interoperability with JavaScript from C#.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.