当前位置: 首页 > news >正文

制作浏览器CEFSharp133+X86+win7 之 javascript交互(二)

C#交互代码

注册对象

webview.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
webview.JavascriptObjectRepository.Register("myClass", new AAA(), true);


===========================================================

前端

//CefSharp.BindObjectAsync('myClass');
//myClass.say();

CefSharp.BindObjectAsync('myClass').then(function (result) {
myClass.say();
});


---------------------------------------------------------------------------------------------

后端执行js

//不带参数
webview.ExecuteScriptAsync("myClass.say()");

//带参数
var p = {
say2: function (txt) { //前端对象方法
alert(txt);
}
}
webview.ExecuteScriptAsync("p.say2","这是参数");

//执行有返回值的js
var res = await webview.EvaluateScriptAsync("p.say2","asdas");
MessageBox.Show(res.Result.ToString());

---------------------------------------------------------------------------------

浏览器配置

/// <summary>
/// cef浏览器全局设置
/// </summary>
public class CefHelper
{/// <summary>/// 初始化cef引擎/// </summary>public static void Init(){var settings = new CefSettings(){Locale = "zh-CN",AcceptLanguageList = "zh-CN,zh;q=0.8",PersistSessionCookies = true,UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0 Safari/537.36",IgnoreCertificateErrors = true,LogSeverity = LogSeverity.Disable, //禁用日志//为空则将以“隐身模式”创建浏览器//CachePath = AppDomain.CurrentDomain.BaseDirectory + "cef_cache",//Windows上用户“Local Settings\Application Data\CEF\User Data”目录UserDataPath = AppDomain.CurrentDomain.BaseDirectory + "cef_temp"};settings.CefCommandLineArgs.Add("disable-gpu", "1"); // 禁用gpusettings.CefCommandLineArgs.Add("no-proxy-server", "1"); //禁用代理settings.CefCommandLineArgs.Add("proxy-auto-detect", "0"); //禁用代理//settings.CefCommandLineArgs.Add("proxy-server", "ProxyAddress");settings.CefCommandLineArgs.Add("--disable-web-security", "1"); //允许跨域settings.CefCommandLineArgs.Add("--ignore-urlfetcher-cert-requests", "1");//忽略安全证书settings.CefCommandLineArgs.Add("--ignore-certificate-errors", "1");//忽略安全证书settings.CefCommandLineArgs.Add("enable-media-stream", "1"); //允许webRTC//settings.CefCommandLineArgs["enable-system-flash"] = "1";//settings.CefCommandLineArgs.Add("ppapi-flash-version", "32.0.0.171");//settings.CefCommandLineArgs.Add("ppapi-flash-path", @"plugins\pepflashplayer.dll");Cef.EnableHighDPISupport();CefSharpSettings.ConcurrentTaskExecution = true;//CefSharpSettings.LegacyJavascriptBindingEnabled = true;Cef.Initialize(settings);}/// <summary>/// 关闭cef引擎/// </summary>public static void Shutdown(){Cef.Shutdown();try{Directory.Delete($"{AppDomain.CurrentDomain.BaseDirectory}GPUCache", true);Directory.Delete($"{AppDomain.CurrentDomain.BaseDirectory}cef_temp", true);}catch{}}
}--------

启动

public static ChromiumWebBrowser webview;
public FrmMain()
{webview = new ChromiumWebBrowser(App.WebUrl);webview.Dock = DockStyle.Fill;webview.DownloadHandler = new DownloadHandler();webview.MenuHandler = new MenuHandler();webview.JavascriptObjectRepository.Register("myClass", new AAA(), true);Controls.Add(webview);CheckForIllegalCrossThreadCalls = false;InitializeComponent();}

-----------------------------------------------------------
WPF

<hc:Window
x:Class="HPRT.Com.Wpf.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:hwndhost="clr-namespace:CefSharp.Wpf.HwndHost;assembly=CefSharp.Wpf.HwndHost"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="{Binding Version, StringFormat='浏览器{0}'}"
Width="800"
Height="450"
NonClientAreaBackground="#1890ff"
NonClientAreaForeground="White"
WindowState="Maximized"
mc:Ignorable="d">
<hwndhost:ChromiumWebBrowser x:Name="browser" Address="{Binding Address}" />
</hc:Window>


--------------------------------------------------------------

Saving Downloads
To enable saving of downloaded files you need to assign an instance of IDownloadHandler to the ChromiumWebBrowser.DownloadHandler property.

The examples below will use the Fluent implementation for ease of use, you can use any of the following:

Create an inline implementing using CefSharp.Fluent.DownloadHandler.Create
Create a class that inherits from DownloadHandler and override only the methods you require.
Create a class that directly implements IDownloadHandler interface.
Always save to specific folder
using CefSharp.Fluent;

//Save all files to temp folder, update to whatever suites you.
var userTempPath = System.IO.Path.GetTempPath();

chromiumWebBrowser.DownloadHandler =
DownloadHandler.UseFolder(userTempPath,
(chromiumBrowser, browser, downloadItem, callback) =>
{
// To access the UI you'll need to use the Dispatcher.InvokeAsync (WPF)
// or Control.BeginInvoke (WinForms)
if(downloadItem.IsComplete)
{
//TODO: Add code here
}
else if(downloadItem.IsCancelled)
{
//TODO: Add code here
}
});
Ask user where to save files
using CefSharp.Fluent;

chromiumWebBrowser.DownloadHandler =
Fluent.DownloadHandler.AskUser((chromiumBrowser, browser, downloadItem, callback) =>
{
// To access the UI you'll need to use the Dispatcher.InvokeAsync (WPF)
// or Control.BeginInvoke (WinForms)
if(downloadItem.IsComplete)
{
//TODO: Add code here
}
else if(downloadItem.IsCancelled)
{
//TODO: Add code here
}
});
Save download WPF Example
A simple WPF example might look something like the following:

using CefSharp.Fluent;

browser.DownloadHandler = CefSharp.Fluent.DownloadHandler
.Create()
.CanDownload((chromiumWebBrowser, browser, url, requestMethod) =>
{
//All all downloads
return true;
})
.OnBeforeDownload((chromiumWebBrowser, browser, downloadItem, callback) =>
{
UpdateDownloadAction("OnBeforeDownload", downloadItem);

        callback.Continue("", showDialog: true);

    }).OnDownloadUpdated((chromiumWebBrowser, browser, downloadItem, callback) =>
{
UpdateDownloadAction("OnDownloadUpdated", downloadItem);
})
.Build();

private void UpdateDownloadAction(string downloadAction, DownloadItem downloadItem)
{
// Invoke on the WPF UI Thread
this.Dispatcher.InvokeAsync(() =>
{
var viewModel = (BrowserTabViewModel)this.DataContext;
viewModel.LastDownloadAction = downloadAction;
viewModel.DownloadItem = downloadItem;
});
}
Hide popup window opened by download
For downloads that open a popup window it maybe desirable to hide that popup once the download has started, closing once complete or cancelled.

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWindowVisible(IntPtr hWnd);

[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

var tempPath = System.IO.Path.GetTempPath();

browser.DownloadHandler =
Fluent.DownloadHandler.UseFolder(tempPath,
(chromiumBrowser, browser, downloadItem, callback) =>
{
// To access the UI you'll need to use the Dispatcher.InvokeAsync (WPF)
// or Control.BeginInvoke (WinForms)
if (downloadItem.IsComplete || downloadItem.IsCancelled)
{
if (browser.IsPopup && !browser.HasDocument)
{
browser.GetHost().CloseBrowser(true);
}
}
//TODO: You may wish to customise this condition to better suite your
//requirements. 
else if(downloadItem.ReceivedBytes < 100)
{
var popupHwnd = browser.GetHost().GetWindowHandle();

                var visible = IsWindowVisible(popupHwnd);
if(visible)
{
const int SW_HIDE = 0;
ShowWindow(popupHwnd, SW_HIDE);
}
}
});

阿雪技术观


在科技发展浪潮中,我们不妨积极投身技术共享。不满足于做受益者,更要主动担当贡献者。无论是分享代码、撰写技术博客,还是参与开源项目维护改进,每一个微小举动都可能蕴含推动技术进步的巨大能量。东方仙盟是汇聚力量的天地,我们携手在此探索硅基生命,为科技进步添砖加瓦。

Hey folks, in this wild tech - driven world, why not dive headfirst into the whole tech - sharing scene? Don't just be the one reaping all the benefits; step up and be a contributor too. Whether you're tossing out your code snippets, hammering out some tech blogs, or getting your hands dirty with maintaining and sprucing up open - source projects, every little thing you do might just end up being a massive force that pushes tech forward. And guess what? The Eastern FairyAlliance is this awesome place where we all come together. We're gonna team up and explore the whole silicon - based life thing, and in the process, we'll be fueling the growth of technology.

http://www.dtcms.com/a/323347.html

相关文章:

  • Javaweb - 14.1 - 前端工程化
  • 从依赖外部提示的显式思维链(CoT),到内部自洽的内化推理(Internalized Reasoning)
  • ConcurrentHashMap源码详解
  • 虚拟手机号工具使用
  • 年轻新标杆!东方心绣脸韧带年轻技术升级发布
  • 基于大语言模型的智能问答系统研究
  • 谷歌官方性能文档:Android 动态性能框架优化Performance Hint API
  • Go 实用指南:如何执行 Skyline 查询(Pareto 最优点筛选)
  • [激光原理与应用-201]:光学器件 - 增益晶体 - 概述
  • Dell PowerEdge: Servers by generation (按代系划分的服务器)
  • leetcode 283. 移动零 - java
  • 【12】 神经网络与深度学习(下)
  • [激光原理与应用-204]:光学器件 - LD激光二极管工作原理以及使用方法
  • 网络超时处理与重试机制:Go最佳实践
  • 【R语言】多样本单细胞分析_SCTransform+Harmony方案(2)
  • Q-learning强化算法万字详解
  • 【工作流引擎】Flowable 和 Activiti
  • 《算法导论》第 15 章 - 动态规划
  • Python大数据分析——AdaBoost、GBDT、SMOTE与XGBoost算法模型
  • Slab 算法浅析
  • go数据处理之textproto.Pipeline
  • 词向量基础:从独热编码到分布式表示的演进
  • BeanDefinition 与 Bean 生命周期(面试高频考点)
  • 第十九天-输入捕获实验
  • 第十四届蓝桥杯青少年组省赛 编程题真题题解
  • 内存+磁盘混合存储数据库——平衡设备的“快”与“稳”
  • drippingblues靶机教程
  • 掌握长尾关键词SEO优化技巧
  • 202506 电子学会青少年等级考试机器人三级器人理论真题
  • 【Datawhale AI夏令营第三期】多模态RAG