当前位置: 首页 > 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.xdnf.cn/news/1266193.html

相关文章:

  • C++-AVL树
  • 词向量基础:从独热编码到分布式表示的演进
  • 微软将于 10 月停止混合 Exchange 中的共享 EWS 访问
  • Codeforces 思维训练(二)
  • [激光原理与应用-206]:光学器件 - SESAM - 基本结构与工作原理
  • 爬虫攻防战:反爬与反反爬全解析
  • 跨境电商系统开发:ZKmall开源商城的技术选型与代码规范实践
  • sqli-labs通关笔记-第40关 GET字符型堆叠注入(单引号括号闭合 手工注入+脚本注入两种方法)
  • 多级缓存详解
  • 【能碳建设1】用AI+开源打造物联网+能碳管理+交易SaaS系统的最短路径实施指南
  • 软件定义车辆加速推进汽车电子技术
  • 快速使用selenium+java案例
  • [Linux]学习笔记系列 -- [arm][lds]
  • 2022 RoboCom 世界机器人开发者大赛-本科组(国赛)
  • 前端工程化:从构建工具到性能监控的全流程实践
  • 2G内存的服务器用宝塔安装php的fileinfo拓展时总是卡死无法安装成功的解决办法
  • Ubuntu下搭建LVGL模拟器
  • 【第2.1话:基础知识】基于Ubuntu的ROS环境搭建与车辆可视化编程实践:初学者指南及RVIZ应用(含作业及代码)
  • Ubuntu Server 22 虚拟机空间扩容
  • ubuntu dpkg命令使用指南
  • 从零玩转Linux云主机:免费申请、连接终端、命令速查表
  • 【SQL进阶】用EXPLAIN看透SQL执行计划:从“盲写“到“精准优化“
  • 【JavaEE】(11) 前端基础三件套
  • 比亚迪第五代DM技术:AI能耗管理的深度解析与实测验证
  • 数学与应用数学:到底有啥区别?
  • Kafka学习记录
  • 建筑物实例分割数据集-9,700 张图片 城市规划与发展 灾害评估与应急响应 房地产市场分析 智慧城市管理 地理信息系统(GIS) 环境影响评估
  • Java安全-组件安全
  • 关于灰度图像相似度的损失函数(笔记)
  • C++安全异常设计