CefSharp之C#与JS互相调用

看了好些偏这类文章,但很多都是远古世界的代码,已经跑不通了,写个随笔,帮后面的人跳坑。

 

先上效果,界面丑不要在意这些细节

 

 

 示例:简单粗暴,直接三二一上代码

一、HTML代码

复制代码

复制代码
<!DOCTYPE html>
<html style="overflow: hidden;">
<head>
    <title></title>
    <link type="text/css" href="../Content/css/framework-font.css" rel="stylesheet">
    <!-- jQuery相关引用 -->
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.4.0/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
</head>
<body >
    <div>
        <button onclick="test1()">测试弹出框</button>
        <button onclick="test2()">读取身份证信息</button>
        <button id="btn_play">播放</button>
        身份证信息<textarea id="idcardmsg"></textarea>
    </div>
<script>
    function test1() {
        bound.showAlertMsg("我是来自HTML的消息");
    }
 
    function test2() {
        var result = bound.readIdCard();
        $("#idcardmsg").val(result);
    }

    function GetCef() {
        //控制台打印数据,验证一下
        console.log(bound.getSrc());
        return bound.getSrc();
    } 

    $(function () {
        $("#btn_play").click(function () {
            var txt = GetCef();
            console.log("button.play---" + txt);
            alert(txt);
        });
    });
 
</script>
</body>
</html>
复制代码

 


 
复制代码


本地测试HTML文件的可以放在程序根目录下

String page = string.Format(@"{0}\TestDemo.html", Application.StartupPath);方便测试

 二、C# 的Form代码

复制代码
 1 using CefSharp;
 2 using CefSharp.WinForms;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.ComponentModel;
 6 using System.Data;
 7 using System.Drawing;
 8 using System.IO;
 9 using System.Linq;
10 using System.Text;
11 using System.Threading.Tasks;
12 using System.Windows.Forms;
13 
14 namespace WindowsFormsApp1
15 {
16     public partial class Form1 : Form
17     {
18         19         
20         public Form1()
21         {
22             InitializeComponent();
23             InitializeChromium();
24         }
25 
26         private void Form1_Load(object sender, EventArgs e)
27         {
28             
29         }
30 
31 
32         /// <summary>
33         /// 初始化浏览器并启动
34         /// </summary>
35         public void InitializeChromium()
36         {
37             CefSettings settings = new CefSettings();
38             String page = string.Format(@"{0}\TestDemo.html", Application.StartupPath);
39 
40             if (!File.Exists(page))
41             {
42                 MessageBox.Show("地址不对,我找不到");
43             }
44 
45             // Initialize cef with the provided settings
46             Cef.Initialize(settings);
47             // Create a browser component
48             
49             chromiumWebBrowser1.LoadUrl(page);
50             chromiumWebBrowser1.MenuHandler = new MenuHandler();
51 
52             //需要添加此句代码,否则下面执行会报错
53             chromiumWebBrowser1.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
54             CefSharpSettings.WcfEnabled = true;
55             chromiumWebBrowser1.JavascriptObjectRepository.Register("bound", new CefCustomObject(chromiumWebBrowser1, this), isAsync: false, options: BindingOptions.DefaultBinder);
61             

         // Allow the use of local resources in the browser 62 BrowserSettings browserSettings = new BrowserSettings(); 63 chromiumWebBrowser1.BrowserSettings = browserSettings; 64 65 } 66 67 68 /// <summary> 69 /// 关闭窗口时释放浏览器资源 70 /// </summary> 71 /// <param name="sender"></param> 72 /// <param name="e"></param> 73 private void Form1_FormClosing(object sender, FormClosingEventArgs e) 74 { 75 // 关闭时注销释放内核 76 try 77 { 78 chromiumWebBrowser1.CloseDevTools(); 79 chromiumWebBrowser1.GetBrowser().CloseBrowser(true); 80 } 81 catch { } 82 83 try 84 { 85 if (chromiumWebBrowser1 != null) 86 { 87 chromiumWebBrowser1.Dispose(); 88 Cef.Shutdown(); 89 } 90 } 91 catch { } 92 } 93 } 94 }
复制代码

三、要注册的 CefCustomObject 类

复制代码

复制代码
 1 using CefSharp.WinForms;
 2 using CefSharp;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 using System.Windows.Forms;
 9 using System.Security.Policy;
10 
11 namespace WindowsFormsApp1
12 {
13     public class CefCustomObject
14     {
15         // Declare a local instance of chromium and the main form in order to execute things from here in the main thread
16         private static ChromiumWebBrowser _instanceBrowser = null;
17         // The form class needs to be changed according to yours
18         private static Form1 _instanceMainForm = null;
19 
20         TextBox url;
21         public CefCustomObject(ChromiumWebBrowser originalBrowser, Form1 mainForm)
22         {
23             _instanceBrowser = originalBrowser;
24             _instanceMainForm = mainForm;
25         }
26 
27         /// <summary>
28         /// 窗口加载完毕时需要触发的全局JS对象;
29         /// </summary>
30         public void OnFrameLoadEnd(object sender, FrameLoadEndEventArgs e)
31         {
32             if (e.Frame.IsMain)
33             {
34                 _instanceBrowser.ExecuteScriptAsync(@"
35               document.body.onmouseup = function()
36               {
37                 bound.onSelected(window.getSelection().toString());
38               }
39             ");
40             }
41         }
42 
43         /// <summary>
44         /// 显示一个弹出对话框,前端JS调用的方法
45         /// </summary>
46         /// <param name="msg">传入参数</param>
47         public void ShowAlertMsg(string msg)
48         {
49             MessageBox.Show("The user selected some text [" + msg + "]");
50         }
51 
52         public string getSrc()
53         {
54             return "反手给你个string";
55         }
56 
57         public string ReadIdCard()
58         {
59             // 具体调用读身份证读卡器的方法
60             // IDCardModel model=IDCardSdk.Read();
61             //将身份证信息返回给前端;
62             // return model.ToJson();
63             return "调用失败";
64         }
65     }
66 }
复制代码

 


复制代码

CefSharp版本,安装的话直接在NuGet就好了,也非常快

 

 也没啥的了,除了版本问题可能遇到的坑,都没难点的

posted @   山水未必相逢  阅读(195)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示