C#呼叫JS的幾種方法
cmd呼叫phantomjs
官方資料:http://phantomjs.org/quick-start.html
手動執行
從官方下載phantomjs.exe,拷貝它與要執行的js同目錄
開啟cmd,輸入命令列(參考官方資料的命令列)
phantomjs XX.js 引數1 引數2
獲得結果
使用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/ExcuteJsByPhantomjs
C#呼叫JS庫
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-5003010
3.使用CefSharp創造瀏覽器環境
CefSharp參考我的資料:https://www.cnblogs.com/Lulus/p/7998297.html
(PS:還有幾篇關於CefSharp的資料,在此不一一列出)
4.Microsoft.ClearScript(比較新,沒有實驗)
https://github.com/Microsoft/ClearScript
比較繞的一種方式
控制檯http請求網頁->網頁呼叫js->得到結果js物件->結果返回給控制檯(即時通訊:SignalR)
即時通訊參考我的資料:http://www.cnblogs.com/Lulus/p/8780595.html
比較麻煩的一種方式
JS翻譯成C#……是的,翻譯=.=
以上就是C#呼叫JS的幾種方法的詳細內容,更多關於C#呼叫JS的資料請關注我們其它相關文章!