制作浏览器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.