首页 / JAVASCRIPT / C#调用JS
C#调用JS
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#调用JS,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2543字,纯文字阅读大概需要4分钟。
内容图文
手动执行
从官方下载phantomjs.exe,拷贝它与要执行的js同目录
打开cmd,输入命令行(参考官方资料的命令行)
phantomjs XX.js 参数1 参数2
获得结果
使用C#执行
C#代码如下:
//注意:保证phantomjs.exe和js在生成目录下存在string url = "传参";//这里调用cmd.exeProcess pProcess = new Process();//调用phantomjs.exepProcess.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
//引用:Jintstring 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 ̄)づ
内容总结
以上是互联网集市为您收集整理的C#调用JS全部内容,希望文章能够帮你解决C#调用JS所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。