如何在没有WebView的情况下在UWP中用C#执行JavaScript函数

如何在没有WebView的情况下在UWP中用C#执行JavaScript函数,javascript,c#,uwp,Javascript,C#,Uwp,假设我们的C#UWP应用程序项目中包含一个*.js文件,我们希望能够执行该文件中包含的函数 示例JS函数: function myFunction(p1, p2) { return p1 * p2; // The function returns the product of p1 and p2 } 示例C#代码: 公共类SampleObject { 公共采样对象(int a、int b) { 评估的var=> } } 有没有其他方法可以让我们的JS加载一些虚拟We

假设我们的C#UWP应用程序项目中包含一个*.js文件,我们希望能够执行该文件中包含的函数

示例JS函数:

function myFunction(p1, p2) {
return p1 * p2;              // The function returns the product of p1 and p2
}

示例C#代码:

公共类SampleObject
{
公共采样对象(int a、int b)
{
评估的var=>
}
}
有没有其他方法可以让我们的JS加载一些虚拟WebView并从中调用myFunction?
我读过一些关于脉轮的文章,看起来像是某种应该起作用的东西,但我不知道如何以我想要的方式使用它。有几行示例吗?

您需要一个javascript解释器来运行javascript

我在Jint:

您可以使其像以下未经测试的代码片段中那样工作:

如果您想运行js文件,只需读取并运行它

  • 我会使用cscript.exe来运行您的JavaScript-请参阅以获取有关这方面的信息
  • 使用System.Diagnostics.Process对象调用cscript.exe
  • 使用ProcessStartInfo对象传递JavaScript文件的路径
  • 设置事件以从StandardOutput和StandardError通道捕获输出。请注意,并非StandardError返回的所有内容都一定是错误。为了方便起见,我为Process类创建了一个包装器,名为cManagedProcess:

    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Text;
    using System.Threading;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string sScriptPath = @"C:\temp\test.js";
                File.WriteAllText(sScriptPath, @"
    //Your JavaScript goes here!
    WScript.Echo(myFunction(1, 2));
    
    function myFunction(p1, p2) {
        return p1 * p2; // The function returns the product of p1 and p2
    }
    ");
    
                var oManagedProcess = new cManagedProcess("cscript.exe", sScriptPath);
                int iExitCode = oManagedProcess.Start();
    
                Console.WriteLine("iExitCode = {0}\nStandardOutput: {1}\nStandardError: {2}\n", 
                    iExitCode, 
                    oManagedProcess.StandardOutput,
                    oManagedProcess.StandardError
                    );
    
                Console.WriteLine("Press any key...");
                Console.ReadLine();
            }
        }
    
        public class cManagedProcess
        {
            private Process moProcess;
    
            public ProcessStartInfo StartInfo;
    
            private StringBuilder moOutputStringBuilder;
            public string StandardOutput
            {
                get
                {
                    return moOutputStringBuilder.ToString();
                }
            }
    
            private StringBuilder moErrorStringBuilder;
            public string StandardError
            {
                get
                {
                    return moErrorStringBuilder.ToString();
                }
            }
    
            public int TimeOutMilliSeconds = 10000;
    
            public bool ThrowStandardErrorExceptions = true;
    
            public cManagedProcess(string sFileName, string sArguments)
            {
                Instantiate(sFileName, sArguments);
            }
    
            public cManagedProcess(string sFileName, string sFormat, params object[] sArguments)
            {
                Instantiate(sFileName, string.Format(sFormat, sArguments));
            }
    
            private void Instantiate(string sFileName, string sArguments)
            {
                this.StartInfo = new ProcessStartInfo()
                {
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    RedirectStandardError = true,
                    RedirectStandardOutput = true,
                    FileName = sFileName,
                    Arguments = sArguments
                };
            }
    
            private AutoResetEvent moOutputWaitHandle;
            private AutoResetEvent moErrorWaitHandle;
    
            /// <summary>
            /// Method to start the process and wait for it to terminate
            /// </summary>
            /// <returns>Exit Code</returns>
            public int Start()
            {
                moProcess = new Process();
                moProcess.StartInfo = this.StartInfo;
                moProcess.OutputDataReceived += cManagedProcess_OutputDataReceived;
                moProcess.ErrorDataReceived += cManagedProcess_ErrorDataReceived;
    
                moOutputWaitHandle = new AutoResetEvent(false);
                moOutputStringBuilder = new StringBuilder();
    
                moErrorWaitHandle = new AutoResetEvent(false);
                moErrorStringBuilder = new StringBuilder();
    
                bool bResourceIsStarted = moProcess.Start();
    
                moProcess.BeginOutputReadLine();
                moProcess.BeginErrorReadLine();
    
                if (
                    moProcess.WaitForExit(TimeOutMilliSeconds)
                    && moOutputWaitHandle.WaitOne(TimeOutMilliSeconds)
                    && moErrorWaitHandle.WaitOne(TimeOutMilliSeconds)
                    )
                {
                    if (mbStopping)
                    {
                        return 0;
                    }
    
                    if (moProcess.ExitCode != 0 && ThrowStandardErrorExceptions)
                    {
                        throw new Exception(this.StandardError);
                    }
                    return moProcess.ExitCode;
                }
                else
                {
                    throw new TimeoutException(string.Format("Timeout exceeded waiting for {0}", moProcess.StartInfo.FileName));
                }
            }
    
            private bool mbStopping = false;
            public void Stop()
            {
                mbStopping = true;
                moProcess.Close();
            }
    
    
            private void cManagedProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
            {
                DataRecieved(e, moOutputWaitHandle, moOutputStringBuilder);
            }
    
            private void cManagedProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)
            {
                DataRecieved(e, moErrorWaitHandle, moErrorStringBuilder);
            }
    
            private void DataRecieved(DataReceivedEventArgs e, AutoResetEvent oAutoResetEvent, StringBuilder oStringBuilder)
            {
                if (e.Data == null)
                {
                    oAutoResetEvent.Set();
                }
                else
                {
                    oStringBuilder.AppendLine(e.Data);
                }
            }
        }
    }
    
    使用系统;
    使用系统诊断;
    使用System.IO;
    使用系统文本;
    使用系统线程;
    命名空间控制台应用程序1
    {
    班级计划
    {
    静态void Main(字符串[]参数)
    {
    字符串sScriptPath=@“C:\temp\test.js”;
    File.writealText(sScriptPath,@“
    //你的JavaScript在这里!
    Echo(myFunction(1,2));
    函数myFunction(p1,p2){
    return p1*p2;//函数返回p1和p2的乘积
    }
    ");
    var oManagedProcess=新的cManagedProcess(“cscript.exe”,sScriptPath);
    int iExitCode=oManagedProcess.Start();
    WriteLine(“iExitCode={0}\n标准输出:{1}\n标准错误:{2}\n”,
    IEXit代码,
    oManagedProcess.StandardOutput,
    oManagedProcess.StandardError
    );
    Console.WriteLine(“按任意键…”);
    Console.ReadLine();
    }
    }
    公共类cManagedProcess
    {
    私有进程moProcess;
    公共流程StartInfo StartInfo;
    私有StringBuilder moOutputStringBuilder;
    公共字符串标准输出
    {
    得到
    {
    返回moOutputStringBuilder.ToString();
    }
    }
    私人StringBuilder moErrorStringBuilder;
    公共字符串标准错误
    {
    得到
    {
    返回moErrorStringBuilder.ToString();
    }
    }
    公共int timeoutmillizes=10000;
    public bool throwstandarderroxceptions=true;
    公共cManagedProcess(字符串sFileName、字符串sArguments)
    {
    实例化(sFileName,sArguments);
    }
    公共cManagedProcess(字符串sFileName、字符串sFormat、参数对象[]sArguments)
    {
    实例化(sFileName,string.Format(sFormat,sArguments));
    }
    私有void实例化(字符串sFileName、字符串sArguments)
    {
    this.StartInfo=新流程StartInfo()
    {
    UseShellExecute=false,
    CreateNoWindow=true,
    RedirectStandardError=true,
    重定向标准输出=真,
    FileName=sFileName,
    参数=sArguments
    };
    }
    私有自动resetEvent moOutputWaitHandle;
    私人汽车租赁公司;
    /// 
    ///方法启动进程并等待其终止
    /// 
    ///出口代码
    公共int Start()
    {
    moProcess=新进程();
    moProcess.StartInfo=this.StartInfo;
    moProcess.OutputDataReceived+=cManagedProcess_OutputDataReceived;
    moProcess.ErrorDataReceived+=cManagedProcess\u ErrorDataReceived;
    moOutputWaitHandle=新的自动存储事件(false);
    moOutputStringBuilder=新的StringBuilder();
    MOERROWATHANDLE=新的自动恢复事件(false);
    moErrorStringBuilder=新的StringBuilder();
    bool bResourceIsStarted=moProcess.Start();
    moProcess.BeginOutputReadLine();
    moProcess.BeginErrorReadLine();
    如果(
    moProcess.WaitForExit(超时毫秒)
    &&moOutputWaitHandle.WaitOne(超时毫秒)
    &&moerrrowaithandle.WaitOne(超时毫秒)
    )
    {
    如果(MB停止)
    {
    返回0;
    }
    if(moProcess.ExitCode!=0&&throwstandarderroxceptions)
    {
    抛出新异常(this.StandardError);
    }
    返回moProcess.ExitCode;
    }
    其他的
    {
    抛出新的TimeoutException(string.Format(“等待{0}时超出超时时间”,moProcess.StartInfo.FileName));
    }
    }
    私有bool mbStopping=false;
    公共停车场()
    {
    mbStopping=true;
    moProcess.Close();
    }
    私有void cManagedProcess_OutputDataReceived(对象发送方,DataReceivedEventArgs e)
    {
    收到的数据(e、moOutputWaitHandle、moOutputStringBuilder);
    }
    private void cManagedProcess_ErrorDataReceived(对象发送方,DataReceivedEventArgs e)
    {
    收到的数据(e、moErrorWaitHandle、moErrorStringBuilder);
    }
    收到的私有无效数据(DataReceivedEventArgs e、AutoResetEvent oAutoResetEvent、StringBuilder或StringBuilder)
    {
    
    JintEngine engine = new JintEngine();
    
    engine.Run(@"
      myFunction(p1, p2) { 
        return p1 * p2;
      }";
    
    Console.Write(engine.Run("myFunction(4,5);");
    
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Text;
    using System.Threading;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string sScriptPath = @"C:\temp\test.js";
                File.WriteAllText(sScriptPath, @"
    //Your JavaScript goes here!
    WScript.Echo(myFunction(1, 2));
    
    function myFunction(p1, p2) {
        return p1 * p2; // The function returns the product of p1 and p2
    }
    ");
    
                var oManagedProcess = new cManagedProcess("cscript.exe", sScriptPath);
                int iExitCode = oManagedProcess.Start();
    
                Console.WriteLine("iExitCode = {0}\nStandardOutput: {1}\nStandardError: {2}\n", 
                    iExitCode, 
                    oManagedProcess.StandardOutput,
                    oManagedProcess.StandardError
                    );
    
                Console.WriteLine("Press any key...");
                Console.ReadLine();
            }
        }
    
        public class cManagedProcess
        {
            private Process moProcess;
    
            public ProcessStartInfo StartInfo;
    
            private StringBuilder moOutputStringBuilder;
            public string StandardOutput
            {
                get
                {
                    return moOutputStringBuilder.ToString();
                }
            }
    
            private StringBuilder moErrorStringBuilder;
            public string StandardError
            {
                get
                {
                    return moErrorStringBuilder.ToString();
                }
            }
    
            public int TimeOutMilliSeconds = 10000;
    
            public bool ThrowStandardErrorExceptions = true;
    
            public cManagedProcess(string sFileName, string sArguments)
            {
                Instantiate(sFileName, sArguments);
            }
    
            public cManagedProcess(string sFileName, string sFormat, params object[] sArguments)
            {
                Instantiate(sFileName, string.Format(sFormat, sArguments));
            }
    
            private void Instantiate(string sFileName, string sArguments)
            {
                this.StartInfo = new ProcessStartInfo()
                {
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    RedirectStandardError = true,
                    RedirectStandardOutput = true,
                    FileName = sFileName,
                    Arguments = sArguments
                };
            }
    
            private AutoResetEvent moOutputWaitHandle;
            private AutoResetEvent moErrorWaitHandle;
    
            /// <summary>
            /// Method to start the process and wait for it to terminate
            /// </summary>
            /// <returns>Exit Code</returns>
            public int Start()
            {
                moProcess = new Process();
                moProcess.StartInfo = this.StartInfo;
                moProcess.OutputDataReceived += cManagedProcess_OutputDataReceived;
                moProcess.ErrorDataReceived += cManagedProcess_ErrorDataReceived;
    
                moOutputWaitHandle = new AutoResetEvent(false);
                moOutputStringBuilder = new StringBuilder();
    
                moErrorWaitHandle = new AutoResetEvent(false);
                moErrorStringBuilder = new StringBuilder();
    
                bool bResourceIsStarted = moProcess.Start();
    
                moProcess.BeginOutputReadLine();
                moProcess.BeginErrorReadLine();
    
                if (
                    moProcess.WaitForExit(TimeOutMilliSeconds)
                    && moOutputWaitHandle.WaitOne(TimeOutMilliSeconds)
                    && moErrorWaitHandle.WaitOne(TimeOutMilliSeconds)
                    )
                {
                    if (mbStopping)
                    {
                        return 0;
                    }
    
                    if (moProcess.ExitCode != 0 && ThrowStandardErrorExceptions)
                    {
                        throw new Exception(this.StandardError);
                    }
                    return moProcess.ExitCode;
                }
                else
                {
                    throw new TimeoutException(string.Format("Timeout exceeded waiting for {0}", moProcess.StartInfo.FileName));
                }
            }
    
            private bool mbStopping = false;
            public void Stop()
            {
                mbStopping = true;
                moProcess.Close();
            }
    
    
            private void cManagedProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
            {
                DataRecieved(e, moOutputWaitHandle, moOutputStringBuilder);
            }
    
            private void cManagedProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)
            {
                DataRecieved(e, moErrorWaitHandle, moErrorStringBuilder);
            }
    
            private void DataRecieved(DataReceivedEventArgs e, AutoResetEvent oAutoResetEvent, StringBuilder oStringBuilder)
            {
                if (e.Data == null)
                {
                    oAutoResetEvent.Set();
                }
                else
                {
                    oStringBuilder.AppendLine(e.Data);
                }
            }
        }
    }