欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

C#调用JS的几种方法

时间:2021-07-11 08:42:16|栏目:.NET代码|点击:

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

上一篇:ABP框架中导航菜单的使用及JavaScript API获取菜单的方法

栏    目:.NET代码

下一篇:C# ArrayList、HashSet、HashTable、List、Dictionary的区别详解

本文标题:C#调用JS的几种方法

本文地址:http://www.codeinn.net/misctech/155785.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有