C#調(diào)用JS的幾種方法
cmd調(diào)用phantomjs
官方資料:http://phantomjs.org/quick-start.html
手動執(zhí)行
從官方下載phantomjs.exe,拷貝它與要執(zhí)行的js同目錄
打開cmd,輸入命令行(參考官方資料的命令行)
phantomjs XX.js 參數(shù)1 參數(shù)2
獲得結(jié)果
使用C#執(zhí)行
//注意:保證phantomjs.exe和js在生成目錄下存在 string url = "傳參"; //這里調(diào)用cmd.exe Process pProcess = new Process(); //調(diào)用phantomjs.exe pProcess.StartInfo.FileName = $"phantomjs.exe所在路徑(可以是相對路徑)"; pProcess.StartInfo.RedirectStandardOutput = true; pProcess.StartInfo.UseShellExecute = false; pProcess.EnableRaisingEvents = false; //在phantomjs.exe里面執(zhí)行的命令 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(); //取出計算結(jié)果 Console.WriteLine(output[0]); pProcess.Close(); JS如下: function Test() { //創(chuàng)建phantomjs對象 var system = require('system'); //取出參數(shù) var data = system.args[1]; console.log(Math.floor(data)); } Test(); phantom.exit();
示例代碼:https://github.com/zLulus/NotePractice/tree/dev3/Console/CodeLibrary/ExcuteJsByPhantomjs
C#調(diào)用JS庫
1.jint:https://github.com/sebastienros/jint
可用,但是沒有JS的環(huán)境
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
3.使用CefSharp創(chuàng)造瀏覽器環(huán)境
CefSharp參考我的資料:https://www.cnblogs.com/Lulus/p/7998297.html
(PS:還有幾篇關(guān)于CefSharp的資料,在此不一一列出)
4.Microsoft.ClearScript(比較新,沒有實驗)
https://github.com/Microsoft/ClearScript
比較繞的一種方式
控制臺http請求網(wǎng)頁->網(wǎng)頁調(diào)用js->得到結(jié)果js對象->結(jié)果返回給控制臺(即時通訊:SignalR)
即時通訊參考我的資料:http://www.cnblogs.com/Lulus/p/8780595.html
比較麻煩的一種方式
JS翻譯成C#……是的,翻譯=.=
以上就是C#調(diào)用JS的幾種方法的詳細(xì)內(nèi)容,更多關(guān)于C#調(diào)用JS的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#通過XML節(jié)點屬性/屬性值讀取寫入XML操作代碼實例
本文主要介紹C#通過XML節(jié)點屬性、屬性值對XML的讀取,寫入操作,大家參考使用吧2013-11-11