背景
在Windows上c#调用JavaScript常用V8.NET,项目迁移到 Linux 才注意到v8不支持Linux,遂改为JavaScriptEngineSwitcher.ChakraCore(直接在nugget上搜索JavaScriptEngine)
使用
引入nugget包-JavaScriptEngineSwitcher.ChakraCore
代码调用js文件即可:
using JavaScriptEngineSwitcher.ChakraCore;
using JavaScriptEngineSwitcher.Core;
using System.Text;
namespace Program
{
internal static class Sign
{
private const string JsPath = "demo.js";
public static string GetSign(string cityid)
{
string result;
var switcher = JsEngineSwitcher.Current;
switcher.EngineFactories.Add(new ChakraCoreJsEngineFactory());
switcher.DefaultEngineName = ChakraCoreJsEngine.EngineName;
using IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine();
engine.ExecuteFile(JsPath, Encoding.UTF8);
//调用JS文件中的方法、传入参数
result = engine.CallFunction<string>("start", cityid);
return result;
}
}
}
另外avaScriptEngineSwitcher也有V8及其跨平台库,记录一下: