C#和网页js互调代码
1、先写个网页放在主程序目录下:test.html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>测试网页</title> <script> function MyFunc(num) { alert("大家好,这是js代码中的Alert,我将返回30!"); return 30 + num; } </script> </head> <body> <input type="button" onclick="window.external.MyMessageBox(‘javascript访问C#代码‘);" value="点击测试调用C#中的方法!" /> </body> </html>
2、打开WinForm,拖个按钮,拖个WebBrowser。
3、写C#代码并测试
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WebWithForm { [System.Runtime.InteropServices.ComVisible(true)] public partial class Form1 : Form { public Form1() { InitializeComponent(); this.webBrowser2.ObjectForScripting = this; } private void Form1_Load(object sender, EventArgs e) { this.webBrowser2.Navigate(Application.StartupPath + "\\test.html"); } private void button1_Click(object sender, EventArgs e) { var result = this.webBrowser2.Document.InvokeScript("MyFunc", new object[] { 30 }); this.Text = this.webBrowser2.Version.ToString(); label1.Text = "网页返回:" + result; } public void MyMessageBox(string message) { MessageBox.Show("这是C#的MessageBox提示:" + message); } } }
4、运行效果:
时间: 2024-10-03 23:04:47