用C#运行Javascript最可靠的方法

Most reliable way to run Javascript in C#?

本文关键字:方法 运行 Javascript      更新时间:2023-09-26

首先我尝试从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 'error with spaces     '; }";
head.AppendChild(scriptEl);
var result = webBrowser1.Document.InvokeScript("test", new object[] { "sayHello" });

它几乎完美地工作。它知道windowalert是什么……唯一的问题是它显然在ECMA3上运行,所以当我测试"abc ".trim()时,它无法执行。

我的第二次尝试是Javascript.NET.

using (JavascriptContext context = new JavascriptContext())
{
    // Setting external parameters for the context
    //context.SetParameter("console", new SystemConsole());
    context.SetParameter("message", "Hello World !           ");
    // Script
    string script = @"
        alert(message.trim());
    ";
    // Running the script
    context.Run(script);
}

不幸的是,它不知道alertwindowdocumentconsole。。。是。除非我告诉它设置上下文参数。

还有什么?我可以尝试一些无头浏览器并使用Process调用吗?

如果你想运行JavaScript服务器端,我建议你使用PhantomJS。它允许您使用JavaScript和命令行参数从命令行运行完整的WebKit浏览器。

JavaScript绝对不再只是用于客户端脚本。正如Cameron所说,如果您需要DOM,PhantomJS是非常棒的。如果你不这样做,NodeJS是一个拥有丰富库的明确选择。