javascript與c#相互調用

首先創建網頁:javascript

<html> <head> <meta http-equiv="Content-Language" content="zh-cn"> <script language="javascript" type="text/javascript"> <!-- 提供給C#程序調用的方法 --> function messageBox(message) { alert(message); } </script> </head> html

<body> <!-- 調用C#方法 --> <button onclick="window.external.MyMessageBox('javascript訪問C#代碼')" > javascript訪問C#代碼</button> </body> </html> java

2、創建Windows應用程序web

  1. 建立Windows應用程序項目
  2. 在Form1窗體中添加WebBrowser控件
  3. 在Form1類的上方添加

[System.Runtime.InteropServices.ComVisibleAttribute(true)]ui

這是爲了將該類設置爲com可訪問。若是不進行該聲明將會出錯。出錯信息以下圖所示:this

如:code

[System.Runtime.InteropServices.ComVisibleAttribute(true)]orm

public partial class Form1 : Formhtm

4.初始化WebBrowser的Url與ObjectForScripting兩個屬性。對象

Url屬性:WebBrowser控件顯示的網頁路徑

ObjectForScripting屬性:該對象可由顯示在WebBrowser控件中的網頁所包含的腳本代碼訪問。

將Url屬性設置爲須要進行操做的頁的URL路徑。

JavaScript經過window.external調用C#公開的方法。即由ObjectForScripting屬性設置的類的實例中所包含的公共方法。具體設置例子以下:

System.IO.FileInfo file = new System.IO.FileInfo("index.htm");

// WebBrowser控件顯示的網頁路徑

webBrowser1.Url = new Uri(file.FullName);

// 將當前類設置爲可由腳本訪問

webBrowser1.ObjectForScripting = this;

5.C#調用JavaScript方法

經過WebBrowser類的Document屬性中的InvokeScript方法調用當前網頁的Javascript方法。如:

// 調用JavaScript的messageBox方法,並傳入參數

object[] objects = new object[1];

objects[0] = "C#訪問JavaScript腳本";

webBrowser1.Document.InvokeScript("messageBox", objects);

完整代碼以下:

[System.Runtime.InteropServices.ComVisibleAttribute(true)]

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent(); 

   System.IO.FileInfo file = new System.IO.FileInfo("index.htm"); 

   // WebBrowser控件顯示的網頁路徑 

   webBrowser1.Url = new Uri(file.FullName); 

   // 將當前類設置爲可由腳本訪問 

   webBrowser1.ObjectForScripting = this;

}

private void button1_Click(object sender, EventArgs e)

{ 

   // 調用JavaScript的messageBox方法,並傳入參數 

   object[] objects = new object[1]; 

   objects[0] = "C#訪問JavaScript腳本"; 

   webBrowser1.Document.InvokeScript("messageBox", objects);

}

// 提供給JavaScript調用的方法

public void MyMessageBox(string message)

{

MessageBox.Show(message);

} }

end.

相關文章
相關標籤/搜索