c#使用webbrowser控件与javascript交互

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.C#windows窗体应用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代码如下(通过vs2008创建的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”);
// WebBrowser控件显示的网页路径
this.webBrowser1.Url = new Uri(file.FullName);
// 将当前类设置为可由脚本访问
this.webBrowser1.ObjectForScripting =this;

}

private void button1_Click(object sender, EventArgs e)
{

}
// 提供给JavaScript调用的方法
public void MyMessageBox(string message)
{
MessageBox.Show(message);
}

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{

}

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 onclick=”window.external.MyMessageBox(‘javascript访问C#代码’)” >
javascript访问C#代码</button>
</body>
</html>

配置运行成功的话,可以看到相互调用的效果,希望对需要的童鞋有用!

1 comment to c#使用webbrowser控件与javascript交互

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Protected by WP Anti Spam