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

Asked

Viewed 1,256 times

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 the objects window, alert, but the problem is it looks like it runs on ECMA3 when I tested it "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 he doesn’t know the 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 exceptions are not released.

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

  • Have you tried Scriptmanager.Registerclientscriptblock? http://msdn.microsoft.com/en-us/library/bb350750(v=vs.110). aspx

  • @Rodrigoreis this runs js on the client side, I want to run on the server side.

  • @Brunolm You want to access objects like alert, window and document on the server?

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 for Visual Studio that uses this method to test units with Typescript. Tstestadapter with source code on Github. The same can be done for pure Javascript.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.