C#調用JS


cmd調用phantomjs

官方資料:http://phantomjs.org/quick-start.html

手動執行

從官方下載phantomjs.exe,拷貝它與要執行的js同目錄
打開cmd,輸入命令行(參考官方資料的命令行)

phantomjs XX.js 參數1 參數2

獲得結果

使用C#執行

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#……是的,翻譯=.=

 

寫完了很開心,結案么么噠(づ ̄ 3 ̄)づ


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM