169
技術社區[雲棲]
C#通過webbrowser控件與javascript交互
1.C#裏調用控件裏麵網頁的js函數
//調用JavaScript的messageBox方法,並傳入參數
object[] objects = new object[1];
objects[0] = “C#訪問JavaScript腳本";
this.webBrowser1.Document.InvokeScript(“messageBox", objects);//object就是傳入的參數,而messageBox則是網頁中預定義好的js函數。
通過這種方式C#裏麵就可以執行Javascript函數,可以把上麵的代碼放到一個button的click事件裏麵。
2.webbrowser控件裏網頁js調用C#窗體的函數
首先需要在代碼裏麵加上
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form{
…..//
}
這樣使得C#的com對象是對網頁裏的javascript可見的。
然後在嵌入網頁裏麵通過“window.external.MyMessageBox(‘javascript訪問C#代碼’)" ,即通過window.external捕獲調用c#定義好的函數。
具體Form.cs代碼如下(通過vs創建的c#window窗體應用,拖拽上一個webbrowser控件和button控件。):
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
System.IO.FileInfo file = new System.IO.FileInfo("test.html");
this.webBrowser1.Url = new Uri(file.FullName); // WebBrowser控件顯示的網頁路徑
this.webBrowser1.ObjectForScripting =this;// 將當前類設置為可由腳本訪問
}
//提供給JavaScript調用的方法
public void MyMessageBox(string message)
{
MessageBox.Show(message);
}
private void button1_Click_1(object sender, EventArgs e)
{
//調用JavaScript的messageBox方法,並傳入參數
object[] objects = new object[1];
objects[0] = “C#訪問JavaScript腳本";
this.webBrowser1.Document.InvokeScript("messageBox", objects);
}
}
test.html內容比較簡單:
<html>
<head>
<meta http-equiv="Content-Language" content="zh-cn">
<script language="javascript" type="text/javascript">
<!– 提供給C#程序調用的方法 –>
function messageBox(message)
{
alert(message);
}
</script>
</head>
<body>
<!– 調用C#方法 –>
<button >javascript訪問C#代碼</button>
</body>
</html>
配置運行成功的話,可以看到相互調用的效果
最後更新:2017-04-03 15:21:43