是通过使用WebBrowser控件来实现的。WebBrowser控件是一个嵌入式的浏览器控件,可以在Windows应用程序中显示和操作网页。
在C#.NET中,可以通过以下步骤隐藏调用Javascript函数:
下面是一个示例代码:
using System;
using System.Windows.Forms;
namespace WindowsFormsApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.DocumentCompleted += WebBrowser1_DocumentCompleted;
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("https://example.com");
}
private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.AbsolutePath != webBrowser1.Url.AbsolutePath)
return;
var script = "function myFunction(param) { return 'Hello ' + param; }";
webBrowser1.Document.InvokeScript("eval", new object[] { script });
var result = webBrowser1.Document.InvokeScript("myFunction", new object[] { "World" });
MessageBox.Show(result.ToString());
}
}
}
在上述示例中,首先在Form的构造函数中订阅了WebBrowser控件的DocumentCompleted事件。在Form的Load事件中,使用Navigate方法加载了一个网页。
在DocumentCompleted事件中,首先通过eval函数在网页中注入了一个名为myFunction的Javascript函数。然后使用InvokeScript方法调用了myFunction函数,并传递了一个参数"World"。最后,通过MessageBox显示了myFunction函数的返回值。
这样就实现了从C#.NET中的代码隐藏调用Javascript函数。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云