Form1.cs
using CefSharp; using CefSharp.WinForms; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private ChromiumWebBrowser browser = null; private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { if (browser != null) return; var settings = new CefSettings(); //设置语言环境是中文环境 settings.Locale = "zh_CN"; //浏览器缓存的路径,可以设置到某个磁盘,默认设置是在软件运行目录下面。 settings.CachePath = "cache"; //让浏览器的消息循环在一个单独的线程中执行,建议设置成true,具体含义看看浏览器消息处理。 settings.MultiThreadedMessageLoop = true; //这个我理解不到,只有看源码的注释; settings.ExternalMessagePump = false; //去掉gpu,否则chrome显示有问题 settings.CefCommandLineArgs.Add("disable-gpu", "1"); //远程调试端口 settings.RemoteDebuggingPort = 33229; //设置代理服务器 settings.CefCommandLineArgs.Add("proxyserver", "192.168.1.2:8888"); Cef.Initialize(settings); CefSharpSettings.LegacyJavascriptBindingEnabled = true; browser = new ChromiumWebBrowser("http://127.0.0.1:8011/a.aspx"); browser.ActivateBrowserOnCreation = false; browser.Dock = System.Windows.Forms.DockStyle.Fill; browser.Location = new System.Drawing.Point(0, 0); browser.Name = "chromiumWebBrowser1"; browser.Size = new System.Drawing.Size(800, 450); browser.TabIndex = 0; this.Controls.Add(browser); browser.JavascriptObjectRepository.ResolveObject += (s, eve) => { var repo = eve.ObjectRepository; if (eve.ObjectName == "jsObj") { repo.Register("jsObj", new CallbackObjectForJs(), isAsync: true, options: BindingOptions.DefaultBinder); } }; } private void button2_Click(object sender, EventArgs e) { browser.Reload(); } } public class CallbackObjectForJs { public void showMessage(string msg) { MessageBox.Show(msg); } public void t1(string mm) { MessageBox.Show(mm); } public string t2() { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } } }
a.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="a.aspx.cs" Inherits="a" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://apps.bdimg.com/libs/jquery/1.11.3/jquery.min.js" type="text/javascript"></script> <title></title> </head> <body> <form id="form1" runat="server"> <a href="#" id="btnOK" class="easyui-linkbutton" iconcls="icon-ok" style="width: 100%; height: 32px">塞钱进红包</a> <div> <input id="Text1" type="text" /><input id="Button1" type="button" value="button" /> </div> <script type="text/javascript"> CefSharp.BindObjectAsync("jsObj"); $(function () { $('#Button1').click(function () { jsObj.t2().then((r) => { $("#Text1").val(r); }) }); }) </script> </form> </body> </html>
Download the Microsoft Visual C++ Redistributable for Visual Studio 2015, 2017 and 2019.
https://blog.csdn.net/qiaohuyue/article/details/94737881