官方資料:http://phantomjs.org/quick-start.htmlhtml
從官方下載phantomjs.exe,拷貝它與要執行的js同目錄
打開cmd,輸入命令行(參考官方資料的命令行)git
phantomjs XX.js 參數1 參數2
得到結果github
C#代碼以下:
//注意:保證phantomjs.exe和js在生成目錄下存在
string url = "傳參"; //這裏調用cmd.exe Process pProcess = new Process(); //調用phantomjs.exe pProcess.StartInfo.FileName = $"phantomjs.exe所在路徑(能夠是相對路徑)"; pProcess.StartInfo.RedirectStandardOutput = true; pProcess.StartInfo.UseShellExecute = false; pProcess.EnableRaisingEvents = false; //在phantomjs.exe裏面執行的命令 pProcess.StartInfo.Arguments = $"Test2.js所在路徑(能夠是相對路徑) {url}"; pProcess.Start(); char[] spliter = { '\r' }; StreamReader sReader = pProcess.StandardOutput; string[] output = sReader.ReadToEnd().Split(spliter); foreach (string s in output) Console.WriteLine(s); pProcess.WaitForExit(); //取出計算結果 Console.WriteLine(output[0]); pProcess.Close();
JS以下:
function Test() { //建立phantomjs對象 var system = require('system'); //取出參數 var data = system.args[1]; console.log(Math.floor(data)); } Test(); phantom.exit();
示例代碼:https://github.com/zLulus/NotePractice/tree/dev3/Console/CodeLibrary/ExcuteJsByPhantomjsapi
1.jint:https://github.com/sebastienros/jint
可用,可是沒有JS的環境
jQuery support:https://github.com/sebastienros/jint/issues/240瀏覽器
//引用:Jint
string filePath = $"{Environment.CurrentDirectory}//ExcuteJs//TestJs.js"; string data1 = "1"; string data2 = "2"; string jsCode = System.IO.File.ReadAllText(filePath); var square = new Engine() .SetValue("data1", data1) // define a new variable .SetValue("data2", data2) // define a new variable .Execute(jsCode) // execute a statement .GetCompletionValue() // get the latest statement completion value .ToObject(); // converts the value to .NET
示例代碼:https://github.com/zLulus/NotePractice/tree/dev3/Console/CodeLibrary/ExcuteJs
2.Microsoft.JScript
https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.jscript?redirectedfrom=MSDN&view=netframework-4.8&WT.mc_id=DT-MVP-5003010ui
3.使用CefSharp創造瀏覽器環境url
CefSharp參考個人資料:https://www.cnblogs.com/Lulus/p/7998297.htmlspa
(PS:還有幾篇關於CefSharp的資料,在此不一一列出)命令行
4.Microsoft.ClearScript(比較新,沒有實驗)
https://github.com/Microsoft/ClearScript 翻譯
控制檯http請求網頁->網頁調用js->獲得結果js對象->結果返回給控制檯(即時通信:SignalR)
即時通信參考個人資料:http://www.cnblogs.com/Lulus/p/8780595.html
JS翻譯成C#……是的,翻譯=.=
寫完了很開心,結案麼麼噠(づ ̄ 3 ̄)づ