winform 通过 webbrowser 与 js 交互
之前在使用 cef (可在 winform 或 wpf 程序中嵌入 chrome 内核的网页浏览器的组件)时,使用过在 c# 代码中调用网页 js 的功能,以为是 cef 独有的,最近工作中得知,原来 winform 自带的浏览器控件 webbrowser 中也有这个功能,那么我们就来看看吧。
我们先建一个 winform 窗体 formbrowserjs:
其中左侧是一个 webbrowser 控件,右边有一个 textbox 接收网页发来(调用 c# 方法)的消息,另一个 textbox 提供给我们输入内容,然后点击按钮向网页发送消息(调用网页的 js 方法)。
后台代码比较少:
using system; using system.io; using system.runtime.interopservices; using system.windows.forms; namespace winformpractice { [comvisible(true)] public partial class formbrowserjs : form { public formbrowserjs() { initializecomponent(); webbrowser.navigate(path.combine(application.startuppath, "htmlbrowserjs.html")); webbrowser.objectforscripting = this; } public void showmsgforjs(string msg) { tbrecv.text += $"{msg}\r\n"; } private void btnsend_click(object sender, eventargs e) { webbrowser.document.invokescript("showmsgforcsharp", new []{ tbsend.text }); } } }
我们用 navigate 方法让 webbrowser 导航到一个本地网页”htmlbrowserjs.html” 去,并将其 objectforscripting 设置为当前类,意思就是网页可以调用这个类里的方法,同时还要设置这个类的特性 ——[comvisible (true)]—— 以便将方法暴露出去。
showmsgforjs 方法就是供网页的 js 方法调用的,里面就是把消息显示在接收框里。
发送按钮的方法里面使用了 webbrowser.document.invokescript 方法来调用 js 的方法,第一个参数是方法名,第二个参数是一个 object 数组,这里其实使用的是一个 string 数组。
下面我们来看看那个网页:
<!doctype html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> <script> //alert ("准备就绪"); window.external.showmsgforjs("准备就绪"); function showmsgforcsharp(str) { var msg = "收到消息:" + str; //1、调用 c# 方法; window.external.showmsgforjs(msg); //2、改变网页内容; document.getelementbyid("info").innerhtml += msg + "<br/>"; //3、弹窗; alert(msg); } </script> </head> <body> <div> 通过 webbrowser 让 js 与 c# 代码交互 测试页 </div> <div id="info"></div> </body> </html>
在 script 脚本区,首先通过 window.external.showmsgforjs 调用了 winform 窗体类中的 showmsgforjs 方法,提示” 准备就绪”。
然后是供 c# 使用的 showmsgforcsharp 方法,里面使用了三种方法来显示收到的消息。
最后来看看运行效果吧:
可以看到发送和接收都成功了。
最后奉上 demo 地址:https://gitee.com/dlgcy/practice/tree/master/winformpractice
同步首发: