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 #?