zoukankan      html  css  js  c++  java
  • 一文搞定C#.Net如何调用/交互Javascript

    问题

    2020年了网上C#调用Js的方法还是

    1、引用webbrowser控件,简直是刁难我控制台!

    2、引用Interop.MSScriptControl.dll

            private static object ExecuteScript(string argument, string jsCode)
            {
                MSScriptControl.ScriptControl scriptControl = new MSScriptControl.ScriptControl();
                scriptControl.UseSafeSubset = true;
                scriptControl.Language = "JScript";
                scriptControl.AddCode(jsCode);
                try
                {
                    return scriptControl.Eval(argument);
                }
                catch (Exception exception)
                {
                }
                return null;
            }

    但是此程序集已经长久不更新了,JavaScript ES5不支持,从网上下载的版本:

    报错:

    System.Runtime.InteropServices.COMException:“Retrieving the COM class factory for component with CLSID {0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC} failed due to the following error: 80040154 没有注册类 (0x80040154 (REGDB_E_CLASSNOTREG)).”
    

    解决方案

    nuget引入V8.Net:

    将DLL文件拷贝到输出目录:

    c#调用即可:

    c#/Javascript可以互相传递/调用对象

    private readonly static string JsPath = Directory.GetCurrentDirectory() + "/your.js";
    
            public static object ExecuteJavaScript(string cityid, string page)
            {
                string code = File.ReadAllText(JsPath);
                
                V8Engine engine = new V8Engine();
                engine.RunMarshallingTests();
    
                //定义可以在JS中使用的全局变量,string/value
                engine.GlobalObject.SetProperty("cityid_CSObject", cityid);
                engine.GlobalObject.SetProperty("page_CSObject", page);
                
                //js中return object
                string result = engine.ConsoleExecute(code).AsString;
                return result;
            }
  • 相关阅读:
    《Python自动化运维:技术与最佳实践》
    舍本求末的运维自动化技术热潮
    Policy Gradients
    Machine Learning Notes Ⅵ
    Machine Learning Notes Ⅴ
    Machine Learning Notes Ⅳ
    Machine Learning Notes Ⅲ
    Machine Learning Notes Ⅱ
    Machine Learning Notes Ⅰ
    在Linux系统中如何把文件拷贝到U盘
  • 原文地址:https://www.cnblogs.com/Zdelta/p/14122314.html
Copyright © 2011-2022 走看看