使用微軟官方組件Interop.MSScriptControljavascript
1.msscript.ocx下載的地址 http://www.microsoft.com/downloads/details.aspx?displaylang=zh-cn&FamilyID=D05FCF37-4D9F-4769-9442-0BCEEF907033html
或者點擊此處下載 Interop.MSScriptControl.dlljava
2.項目中引用 msscript.ocx 或者 Interop.MSScriptControl.dllweb
如今經過這個組件的一些方法來執行JS代碼,並接收方法執行後的返回值,實現代碼以下:express
ScriptControlClass sc = new ScriptControlClass(); //申明變量 sc.UseSafeSubset = true; //容許執行不安全的代碼 sc.Language = "JavaScript"; //表示須要解析的語言爲JavaScript sc.AddCode(Properties.Resources.GetTimes); // Properties.Resources 資源文件 string str = sc.Run("time", new object[] { "time()" }).ToString(); //第一個參數爲要執行的方法名,第二個參數爲方法體的傳入參數,特別注意的是當JS方法中沒有傳入參數時,這時傳遞的爲該方法名稱,不填寫的話會拋異常。而後將JS方法執行後的返回結果存儲在變量str中
如下代碼將組件的經常使用屬性以及方法封裝成單獨的類,方便調用。 安全
using System; using MSScriptControl; using System.Text; //導入js文件,導入js 方法字符串,而後執行js方法。 經過msscript.ocx控件執行JS腳本 ,先引用 Interop.MSScriptControl.dll //官網下載: 而後 引用 xxx.ocx就好了 http://www.microsoft.com/downloads/details.aspx?displaylang=zh-cn&FamilyID=D05FCF37-4D9F-4769-9442-0BCEEF907033 namespace csharp中執行js方法 { class script_run { /// <summary> /// 腳本類型 /// </summary> public enum ScriptLanguage { /// <summary> /// JScript腳本語言 /// </summary> JScript, /// <summary> /// VBscript腳本語言 /// </summary> VBscript, /// <summary> /// JavaScript腳本語言 /// </summary> JavaScript } /// <summary> /// 腳本運行錯誤代理 /// </summary> public delegate void RunErrorHandler(); /// <summary> /// 腳本運行超時代理 /// </summary> public delegate void RunTimeoutHandler(); /// <summary> /// ScriptEngine類 /// </summary> public class ScriptEngine { private ScriptControl msc; /// <summary> /// 定義腳本運行錯誤事件 /// </summary> public event RunErrorHandler RunError; /// <summary> /// 定義腳本運行超時事件 /// </summary> public event RunTimeoutHandler RunTimeout; /// <summary> ///構造函數 默認爲 VBscript 腳本類型 /// </summary> public ScriptEngine() : this(ScriptLanguage.VBscript) { } /// <summary> /// 構造函數 /// </summary> /// <param name="language">腳本類型</param> public ScriptEngine(ScriptLanguage language) { this.msc = new ScriptControlClass(); this.msc.UseSafeSubset = true; this.msc.Language = language.ToString(); ((DScriptControlSource_Event)this.msc).Error += new DScriptControlSource_ErrorEventHandler(OnError); ((DScriptControlSource_Event)this.msc).Timeout += new DScriptControlSource_TimeoutEventHandler(OnTimeout); } /// <summary> /// 運行Eval方法 /// </summary> /// <param name="expression">表達式</param> /// <param name="codeBody">函數體</param> /// <returns>返回值object</returns> public object Eval(string expression, string codeBody) { msc.AddCode(codeBody); return msc.Eval(expression); } /// <summary> /// 運行Eval方法 /// </summary> /// <param name="language">腳本語言</param> /// <param name="expression">表達式</param> /// <param name="codeBody">函數體</param> /// <returns>返回值object</returns> public object Eval(ScriptLanguage language, string expression, string codeBody) { if (this.Language != language) this.Language = language; return Eval(expression, codeBody); } /// <summary> /// 運行Run方法 /// </summary> /// <param name="mainFunctionName">入口函數名稱 例如:add</param> /// <param name="parameters">參數:例如:new object(){"",""}</param> /// <param name="codeBody">函數體 例如:fucniton add(int a,int b){return a+b;}</param> /// <returns>返回值object:獲取object.Tostring()</returns> public object Run(string mainFunctionName, object[] parameters, string codeBody) { this.msc.AddCode(codeBody); return msc.Run(mainFunctionName, parameters); } /// <summary> /// 運行Run方法 /// </summary> /// <param name="language">腳本語言</param> /// <param name="mainFunctionName">入口函數名稱</param> /// <param name="parameters">參數</param> /// <param name="codeBody">函數體</param> /// <returns>返回值object</returns> public object Run(ScriptLanguage language, string mainFunctionName, object[] parameters, string codeBody) { if (this.Language != language) this.Language = language; return Run(mainFunctionName, parameters, codeBody); } /// <summary> /// 放棄全部已經添加到 ScriptControl 中的 Script 代碼和對象 /// </summary> public void Reset() { this.msc.Reset(); } /// <summary> /// 獲取或設置腳本語言 /// </summary> public ScriptLanguage Language { get { return (ScriptLanguage)Enum.Parse(typeof(ScriptLanguage), this.msc.Language, false); } set { this.msc.Language = value.ToString(); } } /// <summary> /// 獲取或設置腳本執行時間,單位爲毫秒 /// </summary> public int Timeout { get { return 0; } } /// <summary> /// 設置是否顯示用戶界面元素 /// </summary> public bool AllowUI { get { return this.msc.AllowUI; } set { this.msc.AllowUI = value; } } /// <summary> /// 宿主應用程序是否有保密性要求 /// </summary> public bool UseSafeSubset { get { return this.msc.UseSafeSubset; } set { this.msc.UseSafeSubset = true; } } /// <summary> /// RunError事件激發 /// </summary> private void OnError() { if (RunError != null) RunError(); } /// <summary> /// OnTimeout事件激發 /// </summary> private void OnTimeout() { if (RunTimeout != null) RunTimeout(); } } } }
一、必需要添加微軟官方組件Interop.MSScriptControldom
二、不支持開發x64的程序函數
無需引用其它dll文件,實現代碼以下: ui
/// <summary> /// 獲取JS時間戳 13位 /// </summary> /// <returns></returns> public string GetTimeByJs() { Type obj = Type.GetTypeFromProgID("ScriptControl"); if (obj == null) return null; object ScriptControl = Activator.CreateInstance(obj); obj.InvokeMember("Language", BindingFlags.SetProperty, null, ScriptControl, new object[] { "JavaScript" }); string js = "function time(a, b, msg){ var sum = a + b; return new Date().getTime() + ': ' + msg + ' = ' + sum }"; obj.InvokeMember("AddCode", BindingFlags.InvokeMethod, null, ScriptControl, new object[] { js }); return obj.InvokeMember("Eval", BindingFlags.InvokeMethod, null, ScriptControl, new object[] { "time(a, b, 'a + b')" }).ToString(); }
注意事項:在JS方法中傳遞的參數若是是字符串,參數須要使用引號括起來,不然不須要。this
區別:
一、方法一須要引用dll文件,方法二不須要引用dll文件;
二、方法一不支持開發x64的程序,方法二支持;
三、執行JS方法時,若是傳入的參數是字符串時,在方法二中必需要使用引號括起來,不然不須要,而方法一給JS方法傳參無需使用括號。
根據參數本身生成html代碼,而後交給WebBrowser執行。html文件的代碼以下:
<!DOCTYPE html> <html> <script type="text/javascript" src="http://ui.ptlogin2.qzone.com/js/10141/login_10.js"></script> <script type="text/javascript" > var result=$.Encryption.getEncryption("bada23","","",!1); document.write(result); </script> <body> </body> </html>
忽略腳本錯誤,設置WebBrowser屬性:
C#代碼以下:
void MainFormLoad(object sender, EventArgs e) { webBrowser1.DocumentText=File.ReadAllText(@"C:\Users\Administrator\Desktop\abc.html"); }
void Button1Click(object sender, EventArgs e) { MessageBox.Show(webBrowser1.Document.Body.OuterText); }
效果以下圖所示:
如下補充一下如何使用JS調用C#方法
C#代碼:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Runtime.InteropServices; using System.Security.Permissions; namespace test { [PermissionSet(SecurityAction.Demand, Name ="FullTrust")] [ComVisible(true)]//COM+組件可見 public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { webBrowser1.Document.InvokeScript("Run", new object[] { "CShareFunction" }); } private void Form1_Load(object sender, EventArgs e) { webBrowser1.ObjectForScripting = this;//具體公開的對象,這裏能夠公開自定義對象 webBrowser1.Navigate(Application.StartupPath + "/dom.html"); } public void ShowMsg(string msg) { MessageBox.Show(msg); } } }
html文件的JS代碼:
<html> <head> </head> <body> </body> <script type="text/javascript" charset="utf-8"> function Run(str) { window.external.ShowMsg(str); } </script> </html>
注意的地方:記得給公開對象加上如下標籤屬性
[PermissionSet(SecurityAction.Demand, Name ="FullTrust")] [ComVisible(true)]
運行結果: