MSScriptControl.ScriptControl是C#語言提供的一個COM組件,用來與腳本語言交互執行,支持JScript、VBScript、javascript語言。
工作需要設計一個插件交互庫,需要從C#語言轉移執行主體到JS代碼,並獲取JS代碼返回值給C#語言。
本篇博文在於演示的用法,詳細的MSScriptControl.ScriptControl屬性及方法介紹可以參考另一篇博文:
https://www.cnblogs.com/coolsundy/p/7116123.html
能成功運行的步驟:
一.添加引用。本人使用VS2015,在項目->添加引用->COM->類型庫中勾選Microsoft Script Control 1.0組件。對在解決方案資源管理器中對項目右鍵->屬性->生成->目標平臺x86。x64程序默認沒有註冊MSScriptControl組件,需要手動操作,此處節省麻煩繞過。
二.C#代碼:
注:json3.min.js可在這裏下載:https://cdn.bootcss.com/json3/3.3.2/json3.min.js
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using MSScriptControl;
namespace Test
{
public class Test3
{
public static void Main()
{
string result = "";
ScriptControl scriptControl = new ScriptControlClass();
//scriptControl.UseSafeSubset = true;
scriptControl.Language = "javascript";
string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
scriptControl.AddCode(System.IO.File.ReadAllText(baseDirectory + "hello.js")); // 加載js代碼主體
scriptControl.AddCode(System.IO.File.ReadAllText(baseDirectory + "json3.min.js")); // 加載json庫
//傳入全局變量,可重複傳入刷新值
string jsval1 = "{\"test1\":\"123\",\"test2\":\"456\"}";
string jsval2 = "{\"test1\":\"changed1\",\"test2\":\"changed2\"}";
scriptControl.AddCode(string.Format("var jsval = '{0}'", jsval1));
result = scriptControl.Eval(string.Format(@"globalVarTest('{0}')", jsval1)).ToString();
Console.WriteLine("globalVarTest: " + result);
scriptControl.AddCode(string.Format("var jsval = '{0}'", jsval2));
result = scriptControl.Eval(string.Format(@"globalVarTest('{0}')", jsval2)).ToString();
Console.WriteLine("globalVarTest: " + result);
result = scriptControl.Eval(string.Format(@"sayHello('{0}')", "Helasdsad")).ToString();
Console.WriteLine("sayHello: " + result);
result = scriptControl.Eval(string.Format(@"jsonInTest('{0}')", jsval1)).ToString();
Console.WriteLine("jsonInTest: " + result);
result = scriptControl.Eval("jsonOutTest()").ToString();
Console.WriteLine("jsonOutTest: " + result);
result = scriptControl.Eval("regExpTest()").ToString();
Console.WriteLine("regExpTest: " + result);
// 通過js調用C#方法
TestObj outterObj = new TestObj();
outterObj.test("call1", "call2"); //C#調用
scriptControl.AddObject("outterObj", outterObj);
scriptControl.Eval("outterCall('call3', 'call4')"); //js調用
// 捕獲js內部異常
try{
scriptControl.Eval("exceptionTest1()");
} catch (COMException e) {
Console.WriteLine("exceptionTest1: " + e.Message);
}
try {
scriptControl.Eval("exceptionTest2()");
} catch (COMException e) {
Console.WriteLine("exceptionTest2: " + e.Message);
}
}
}
[ComVisible(true)]
public class TestObj
{
public void test(object obj, string str2)
{
Console.WriteLine("outterCall: " + obj + str2);
}
}
}
三.所使用的javascript代碼,將以下代碼粘貼爲hello.js,連同上面的json3.min.js一起放到項目的debug文件夾中(默認爲Debug模式,其他模式自行變更文件夾)
var tvar = '123asda'; //無用佔位變量
function sayHello(str) {
return "Hello, " + str;
}
function globalVarTest()
{
return jsval;
}
function exceptionTest1()
{
throw "sad"; // 拋出異常
}
function exceptionTest2()
{
sfaafs("|"); // 調用方不存在
}
function jsonInTest(strjson)
{
json = JSON.parse(strjson);
return json['test1'];
}
function jsonOutTest()
{
map = {'x':1, 'y':2};
return JSON.stringify(map);
}
function outterCall(param1, param2)
{
outterObj.test(param1, param2);
}
function regExpTest()
{
return /e/.test("The best things in life are free!"); // return True
}
四.F5執行相關輸出結果
globalVarTest: {"test1":"123","test2":"456"}
globalVarTest: {"test1":"changed1","test2":"changed2"}
sayHello: Hello, Helasdsad
jsonInTest: 123
jsonOutTest: {"x":1,"y":2}
regExpTest: True
outterCall: call1call2
outterCall: call3call4
exceptionTest1: 引發了異常但未捕獲
exceptionTest2: 缺少對象
引發的異常:“System.Runtime.InteropServices.COMException”(位於 * 中)
引發的異常:“System.Runtime.InteropServices.COMException”(位於 * 中)