How can I run Javascript (most current possible) in C #?

2

First I tried to run with a control WebBrowser

WebBrowser webBrowser1 = new WebBrowser();
webBrowser1.Visible = false;
webBrowser1.Navigate("about:blank");
webBrowser1.Document.Write("<html><head></head><body></body></html>");

HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
dynamic scriptEl = webBrowser1.Document.CreateElement("script");

scriptEl.DomElement.text = "function test(fn) { try{ window[fn](); } catch(ex) { return 'abc     '.trim(); } }"
    + "function sayHello() { alert('ha'); throw 'erro      '; }";
head.AppendChild(scriptEl);

var result = webBrowser1.Document.InvokeScript("test", new object[] { "sayHello" });

It works almost perfectly, it understands objects window , alert , but the problem is that it seems to run on ECMA3, when I tested "abc ".trim() failed.

My second attempt was Javascript .NET .

using (JavascriptContext context = new JavascriptContext())
{

    // Setando parametros externos para o contexto
    // context.SetParameter("console", new SystemConsole());
    context.SetParameter("message", "Hello World !           ");

    // Script
    string script = @"
        alert(message.trim());
    ";

    // Rodando o script
    context.Run(script);
}
The problem is that it does not know alert , window , document , console , the only way to recognize is if I implement everything.

I need to test Javascript to see if everything is running normally, to see if there are no errors and see if no exceptions are thrown.

What else is there? How can I run Javascript with C #?

    
asked by anonymous 22.12.2013 / 01:21

1 answer

1

You can run Javascript with PhantomJS . For this it is necessary to invoke it using Process .

try
{
    Process p = new Process();
    ProcessStartInfo psi = new ProcessStartInfo("phantomjs.exe", "arquivo.js");

    // esconde a janela
    psi.UseShellExecute = false;
    psi.CreateNoWindow = true;

    // redireciona a saída do programa para cá
    psi.RedirectStandardOutput = true;

    // inicia o processo
    p.StartInfo = psi;
    p.Start();

    // obtém a saída do programa
    var output = p.StandardOutput.ReadToEnd();

    p.WaitForExit();
}
catch (Exception ex)
{
    // caso seu arquivo.js lance alguma exceção
}

There is an extension to Visual Studio that uses this method to test drives with TypeScript. TSTestAdapter with source code on Github . The same can be done for pure Javascript.

    
22.12.2013 / 01:21