【发布时间】:2010-11-29 01:33:08
【问题描述】:
我在 C# 中使用 webBrowser 控件加载网页,需要调用一个返回字符串值的 JavaScript 函数。我得到了使用 InvokeScript 方法的解决方案,我尝试了很多,但一切都失败了。
【问题讨论】:
标签: c# .net javascript controls webbrowser-control
我在 C# 中使用 webBrowser 控件加载网页,需要调用一个返回字符串值的 JavaScript 函数。我得到了使用 InvokeScript 方法的解决方案,我尝试了很多,但一切都失败了。
【问题讨论】:
标签: c# .net javascript controls webbrowser-control
你能具体说明失败的原因吗?
我下面的示例由一个带有 WebBrowser 和一个按钮的表单组成。
最后称为 y 的对象有句子“我做到了!”。所以对我来说它有效。
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");
}
}
【讨论】:
您可以向 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"});
}
}
【讨论】: