using System;
using System.Windows.Forms;
namespace WindowsFormsApp3
{
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.webBrowser1.ObjectForScripting = this; //这句必须,不然js不能调用C#
this.webBrowser1.Navigate("http://localhost/t.html");
}
/// <summary>
/// 脚本方法
/// </summary>
/// <param name="tag">JS函数名|参数1|参数2</param>
/// <returns></returns>
private object EXEC_JS(WebBrowser webBrowser, string tag)
{
string[] args = tag.Split('|');
if (args.Length == 1)
{
return webBrowser.Document.InvokeScript(args[0], null);
}
else
{
object[] objects = new object[args.Length - 1];
Array.Copy(args, 1, objects, 0, objects.Length);
return webBrowser.Document.InvokeScript(args[0], objects);
}
}
public string Test(string args)
{
MessageBox.Show("c#" + args);
return "你输入的是:" + args;
}
private void button1_Click(object sender, EventArgs e)
{
object returnvalue = EXEC_JS(webBrowser1, "js_fun|参数字符串");
MessageBox.Show("js方法返回值是:" + returnvalue.ToString());
}
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>
<body>
<button onclick="window.external.Test('javascript访问C#代码')" >javascript访问C#代码</button>
<script language="javascript">
window.onload = function()
{
var CS_returnvalue= window.external.Test("aaa");
alert(CS_returnvalue);
}
function js_fun(args){
alert("我是通过js脚本弹出的。你输入的内容是:"+args);
return "JAVASCRIPT";
}
</script>
</body>
</html>
代码很简单,但是今天在公司 半天 都不能调用,不知道 为什么 .