Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get C# to interop with Javascript?

I'd like to host Javascript in my C# program. I would like to allow users to write custom Javascript code, and have my C# program run their functions, as well as allow the users to use my framework code.

Is it possible to do this? If so, how?

Edit: To be clear, I am not using ASP.NET for this project.

like image 270
Erik Forbes Avatar asked Mar 26 '09 21:03

Erik Forbes


4 Answers

you can also use a webbrowser control to host the javascript in a html document, to interact between the two you would make a COM visible class and set an instance of it to the ObjectForScripting property.

Any public members of the 'external' class are now accessible through window.external in javascript. Also, from the managed code side you can use the InvokeScript method of the document to call any javascript functions.

This way it is easy to pass complex objects between the two.

I used this idea quite a bit in this Google Earth Api application. http://fraserchapman.blogspot.com/2008/08/google-earth-plug-in-and-c.html

like image 92
Fraser Avatar answered Oct 17 '22 09:10

Fraser


I'd highly recommend you use the Microsoft Dynamic Langauage Runtime (DLR). It's purpose in life is to facilitate scripting in a .Net environment. The DLR is not script specific so over time more script languages will be built on top of it but at the moment the ones I know about are IronRuby, IronPython and JScript.

like image 20
sipsorcery Avatar answered Oct 17 '22 10:10

sipsorcery


Spidermonkey .NET Is probably what you are looking for.

I'm not sure how developed it is. Buts its basically a port of Mozilla's Spidermonkey Javascript parser engine which I like a lot.

Or you can evaluate it directly

like image 1
bdd Avatar answered Oct 17 '22 11:10

bdd


The way to do this used to be the Windows Script Host, which permitted you to host either JSCript or VBScript.

like image 1
John Saunders Avatar answered Oct 17 '22 11:10

John Saunders