大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺
目录
本节汇总一些关于cefsharp的使用方法,包括c#调用HTML页面中的js,也可以是HTML中的按钮调用c#的方法。汇总后,方便以后使用和查看。
1.取消右键功能
建立MenuHandler类,继承cef中的IContextMenuHandler,并且实现他的接口
public class MenuHandler : IContextMenuHandler
{
void CefSharp.IContextMenuHandler.OnBeforeContextMenu(CefSharp.IWebBrowser browserControl, CefSharp.IBrowser browser, CefSharp.IFrame frame, CefSharp.IContextMenuParams parameters, CefSharp.IMenuModel model)
{
model.Clear();
}
bool CefSharp.IContextMenuHandler.OnContextMenuCommand(CefSharp.IWebBrowser browserControl, CefSharp.IBrowser browser, CefSharp.IFrame frame, CefSharp.IContextMenuParams parameters, CefSharp.CefMenuCommand commandId, CefSharp.CefEventFlags eventFlags)
{
//throw new NotImplementedException();
return false;
}
void CefSharp.IContextMenuHandler.OnContextMenuDismissed(CefSharp.IWebBrowser browserControl, CefSharp.IBrowser browser, CefSharp.IFrame frame)
{
//throw new NotImplementedException();
}
bool CefSharp.IContextMenuHandler.RunContextMenu(CefSharp.IWebBrowser browserControl, CefSharp.IBrowser browser, CefSharp.IFrame frame, CefSharp.IContextMenuParams parameters, CefSharp.IMenuModel model, CefSharp.IRunContextMenuCallback callback)
{
return false;
}
}
使用的时候
chromeBrowser.MenuHandler = new MenuHandler();
2.设置默认语言
CefSettings settings = new CefSettings();
settings.Locale = "zh-CN";// 设置语言
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);//以上这段代码一定要在new ChromiumWebBrowser之前调用
3.设置cookie
可以参考下面读取cookie
var cookieManager = CefSharp.Cef.GetGlobalCookieManager();
cookieManager.SetCookieAsync("http://localhost", new CefSharp.Cookie()
{
Domain = "localhost", //这里是localhost,就会出现设置的值和HTML中的值
Name = "1",
Value = "2",
Expires = DateTime.MinValue
});
4.读取cookie
一般来说,cookie都是浏览器设置好了,所以,可以直接读取cookie。
一、使用js读取
1.HTML
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
this is page 111
<br><a href="page4.html">to page4</a>
<script language=javascript>
document.cookie="username=Tom&age=22";
</script>
</body>
</html>
2.先把HTML发布成网站,代码如下
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;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace cef
{
public partial class Form1 : Form
{
ChromiumWebBrowser webBrower = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//初始化配置
string path = "http://localhost/1.html";
webBrower = new ChromiumWebBrowser(path);
webBrower.Dock = DockStyle.Fill;// 填充方式
this.Controls.Add(webBrower);
}
private void button2_Click(object sender, EventArgs e)
{
Task<CefSharp.JavascriptResponse> t = webBrower.EvaluateScriptAsync("document.cookie");
t.Wait();
var cookie = t.Result.Result;
MessageBox.Show(cookie.ToString());
}
}
}
二、使用cefsharp读取
1.load中载入
2.WebBrower_FrameLoadEnd事件
3.回调
4.建立Cookie读取对象,继承接口 ICookieVisitor
5.效果
所有代码
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;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace cef
{
public partial class Form1 : Form
{
ChromiumWebBrowser webBrower = null;
string cookies;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//初始化配置
string path = "http://localhost/1.html";
webBrower = new ChromiumWebBrowser(path);
webBrower.Dock = DockStyle.Fill;// 填充方式
webBrower.FrameLoadEnd += WebBrower_FrameLoadEnd;
this.Controls.Add(webBrower);
//加载测试页面
webBrower.Load("http://localhost/1.html");
//模拟写入cookie(测试页面,也有一个cookie)
var cookieManager = CefSharp.Cef.GetGlobalCookieManager();
cookieManager.SetCookieAsync("http://localhost", new CefSharp.Cookie()
{
Domain = "localhost", //这里是localhost,就会出现设置的值和HTML中的值
Name = "1",
Value = "2",
Expires = DateTime.MinValue
});
}
private void WebBrower_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
ICookieManager cookieManager = webBrower.GetCookieManager();
CookieVisitor visitor = new CookieVisitor();
visitor.SendCookie += visitor_SendCookie;
cookieManager.VisitAllCookies(visitor);
}
private void visitor_SendCookie(CefSharp.Cookie obj)
{
cookies += obj.Domain.TrimStart('.') + "^" + obj.Name + "^" + obj.Value + "\r\n";
}
public class CookieVisitor : CefSharp.ICookieVisitor
{
public event Action<CefSharp.Cookie> SendCookie;
public void Dispose()
{
}
public bool Visit(CefSharp.Cookie cookie, int count, int total, ref bool deleteCookie)
{
deleteCookie = false;
if (SendCookie != null)
{
SendCookie(cookie);
}
return true;
}
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(cookies.ToString());
}
}
}
三、加载完成后就显示
代码:
public Action GetCookie;
private void Form1_Load(object sender, EventArgs e)
{
GetCookie = () =>
{
Task<CefSharp.JavascriptResponse> t =
webBrower.EvaluateScriptAsync("document.cookie");
t.Wait();
var cookie = t.Result.Result;
this.button2.Text = cookie.ToString();
};
}
private void WebBrower_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
//写后面
this.BeginInvoke(GetCookie);
}
5.c#调用js
使用c#触发HTML中的js。
HTML代码:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<p>点击按钮执行 <em>displayDate()</em> 函数.</p>
<button id="myBtn">点这里</button>
<p id="mytxt">213213</p>
<script>
document.getElementById("myBtn").onclick = function () { displayDate() };
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
</html>
效果是:
c#中调用
第一种方法
第一句是触发点击按钮事件。
第二句是触发文本修改。
webBrower.GetBrowser().MainFrame.ExecuteJavaScriptAsync("document.getElementById('myBtn').click();");
webBrower.GetBrowser().MainFrame.ExecuteJavaScriptAsync("document.getElementById('mytxt').innerHTML='123'");
效果
第二种方法
var script = string.Format("document.getElementById('myBtn').click();");
webBrower.GetMainFrame().ExecuteJavaScriptAsync(script);
6.html调用c#
html代码
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>dd</title>
</head>
<body>
<button onclick="AAA.aa()">html调用C#</button>
</body>
</html>
c#代码
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;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace cef
{
public partial class Form1 : Form
{
private ChromiumWebBrowser chromeBrowser;
public Form1()
{
InitializeComponent();
InitializeChromium();
}
public void InitializeChromium()
{
string indexpage = AppDomain.CurrentDomain.BaseDirectory + @"\1.html";
chromeBrowser = new ChromiumWebBrowser(indexpage);
this.Controls.Add(chromeBrowser);
chromeBrowser.Dock = DockStyle.Fill;
CefSharpSettings.LegacyJavascriptBindingEnabled = true;
CefSharpSettings.WcfEnabled = true;
chromeBrowser.JavascriptObjectRepository.Register("AAA", new CefCustomObject(), isAsync: false, options: BindingOptions.DefaultBinder);
}
}
public class CefCustomObject
{
public void aa()
{
MessageBox.Show("注意方法的命名,坑很多!!!");
}
}
}
效果
注意: 这里调用的方法名称,aa(),之前我写show(),show好像是关键字,一直触发不了,非常的坑人!!!
7. 模拟调用调试F12功能
chromeBrowser.ShowDevTools();
8.关闭窗体
try
{
_instanceBrowser.CloseDevTools();
_instanceBrowser.GetBrowser().CloseBrowser(true);
}
catch { }
try
{
if (_instanceBrowser != null)
{
_instanceBrowser.Dispose();
}
}
catch { }
if (!_instanceMainForm.IsDisposed && _instanceMainForm.IsHandleCreated)
{
var result = _instanceMainForm.BeginInvoke(new Action(() =>
{
if (_instanceMainForm != null && !_instanceMainForm.IsDisposed)
{
_instanceMainForm.Close();
_instanceMainForm.Dispose();
}
}));
_instanceMainForm.EndInvoke(result);
}
9.cefsharp中文文档参考
这是GitHub上面的文档,其中有些不对,可能和版本有关系
CefSharp中文帮助文档 · cefsharp/CefSharp Wiki · GitHub
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/193454.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...