Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to execute javascript code in the .net framework?

i want to be able to execute JavaScript on the server side which is running the .net environment.
so how is it possible to do so? mainly i need text processing functions, i will input a string and get a string returned from JavaScript code.
no window interaction is needed.

like image 859
Karim Avatar asked Apr 25 '12 12:04

Karim


2 Answers

Yes, there are several JS engines which you can use. Jurassic, Jint and IronJS are .NET-based, but you can also interface to others such as the V8 from the Chrome browser or the ActiveScript from IE.

EDIT: Five years later the JS engines native to .NET are somewhat lagging behind (none supports ES6 yet, and IronJS seems abandoned), but we now also have the open-source ChakraCore which is not very hard to integrate and use in .NET with one of the readily available wrappers.

Also, the JavaScriptEngineSwitcher allows using almost any of the existing JS engines from within .NET code through a common interface, so that switching engines does not need changing code.

like image 188
Lucero Avatar answered Sep 28 '22 13:09

Lucero


You can write a JScript.Net file and compile it into an assembly with jsc, then just use that assembly like any other.

Example:

package Your.Desired.Package.Name {
    Class SomeClassName {
        public static function doSomething(foo) }
            var bar;

            // Fairly normal JavaScript code here

            if (foo.match(/sometest/)) {
                // Do something
            }
            else {
                // Do something else
            }
        }
    }
}

Other than the package and class structures, the code in JScript.Net is essentially JavaScript. You even have eval if you want to be evil. :-)

You then compile that into an assembly like this:

jsc /target:library TheFileName.js

...and it produces and assembly in TheFileName.dll.

like image 31
T.J. Crowder Avatar answered Sep 28 '22 11:09

T.J. Crowder