此方法適用於 C#中嵌入WebBrowser(瀏覽器) 經過瀏覽器中加載的頁面與C#的後臺代碼進行交互。
1、C#程序
一、在C#窗體中添加WebBrowser(瀏覽器),將頁面的URL添加到瀏覽器中。
二、窗體代碼添加 using System.Runtime.InteropServices;//和Html頁面交互使用
在類的上一行添加 [ComVisible(true)]//和Html頁面交互使用
在類的構造其中添加
this.webB.ObjectForScripting = this; //和Html頁面交互使用
如:
using System.Runtime.InteropServices;
namespace slgdjb {
[ComVisible(true)]
public partial class Frm_Index : Form
{
public Frm_Index()
{
InitializeComponent();
this.webB.ObjectForScripting = this;
}
}
}
三、添加供Html頁面調用的方法
如:
該方法的方法名即爲Html頁面JS中所要調用的方法名
public string myAction(object para) { //方法內容在此寫 }
四、C#程序調用Html頁面JS方法
首先要得到Html頁面的Document,而後再調用Html頁面的JS方法
如:
HtmlDocument doc = webB.Document; string[] objArray = new string[2]; objArray[0] = "a";
objArray[1] = "b"; //調用Html頁面js方法,JSMonth爲JS方法名,objArray爲傳遞的參數。
//JS中不能接收對象,但能夠接收整形、字符串、字符串數組。 doc.InvokeScript("JSMonth",objArray);
2、Html頁面中JS方法調用C#方法
一、在Html頁面JS中調用C#程序的方法,若C#中的方法有返回值,則JS能夠獲得。
如:
//myAction爲C#中方法的方法名,para爲該方法的參數。
var str = window.external.myAction(para);
二、供C#調用的Html頁面中JS的方法
該方法的方法名即爲C#中所要調用的方法名 obj即爲要傳遞的參數。若傳遞的參數爲數組,則在JS
方法中可直接使用arguments[index(數組參數編號)]表示數組的參數值。arguments爲JS默認數組參數,其好處在於JS方法沒必要寫傳遞的參數。
function JSMonth(obj){
//若obj爲數組,則obj[0]等價於arguments[0];其方法名可改寫爲JSMonth()
}web