23
我正在使用C#中的webBrowser控件來加載網頁,並且需要調用返回字符串值的JavaScript函數。我有一個解決方案,使用InvokeScript方法,我試了很多,但一切都失敗了。在C#中調用Javascript函數webBrowser控件
我正在使用C#中的webBrowser控件來加載網頁,並且需要調用返回字符串值的JavaScript函數。我有一個解決方案,使用InvokeScript方法,我試了很多,但一切都失敗了。在C#中調用Javascript函數webBrowser控件
你能指定什麼失敗嗎?
我在下面的示例包含一個帶有WebBrowser和Button的窗體。
最後稱爲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"});
}
}