在C#webBrowser控件中调用Javascript函数
我正在使用C#中的webBrowser控件加载网页,需要调用返回字符串值的JavaScript函数。我找到了一个使用InvokeScript方法的解决方案,我尝试了很多,但都失败了。你能指定失败的原因吗 我下面的示例由一个带有WebBrowser和按钮的表单组成 最后名为y的对象有一句话“我做到了!”。所以对我来说,它是有效的在C#webBrowser控件中调用Javascript函数,c#,.net,javascript,controls,webbrowser-control,C#,.net,Javascript,Controls,Webbrowser Control,我正在使用C#中的webBrowser控件加载网页,需要调用返回字符串值的JavaScript函数。我找到了一个使用InvokeScript方法的解决方案,我尝试了很多,但都失败了。你能指定失败的原因吗 我下面的示例由一个带有WebBrowser和按钮的表单组成 最后名为y的对象有一句话“我做到了!”。所以对我来说,它是有效的 public partial class Form1 : Form { public Form1() {
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.DocumentText = @"<html><head>
<script type='text/javascript'>
function doIt() {
alert('hello again');
return 'i did it!';
}
</script>
</head><body>hello!</body></html>";
}
private void button1_Click(object sender, EventArgs e)
{
object y = webBrowser1.Document.InvokeScript("doIt");
}
}
公共部分类表单1:表单
{
公共表格1()
{
初始化组件();
webBrowser1.DocumentText=@“
函数doIt(){
警惕(“再次你好”);
返回“我做到了!”;
}
你好;
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
对象y=webBrowser1.Document.InvokeScript(“doIt”);
}
}
您可以向js函数发送参数:
// don't forget this:
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.DocumentText = @"<html><head>
<script type='text/javascript'>
function doIt(myArg, arg2, arg3) {
alert('hello again ' + myArg);
return 'yes '+arg2+' - you did it! thanks to ' +myArg+ ' & ' +arg3;
}
</script>
</head><body>hello!</body></html>";
}
private void button1_Click(object sender, EventArgs e)
{
// get the retrieved object from js into object y
object y = webBrowser1.Document.InvokeScript("doIt", new string[] { "Snir", "Raki", "Gidon"});
}
}
//别忘了这一点:
[权限集(SecurityAction.Demand,Name=“FullTrust”)]
[ComVisible(true)]
公共部分类Form1:Form
{
公共表格1()
{
初始化组件();
webBrowser1.DocumentText=@“
函数doIt(myArg、arg2、arg3){
警报(“再次你好”+myArg);
返回'yes'+arg2+'-您做到了!感谢'+myArg+'&'+arg3;
}
你好;
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
//将从js检索到的对象获取到对象y中
对象y=webBrowser1.Document.InvokeScript(“doIt”,新字符串[]{“Snir”、“Raki”、“Gidon”});
}
}