winform 使用CefSharp嵌套Chromium内核浏览器

1、新建winform 项目.net frame4.8

2、nuget安装CefSharp.WinForms 版本84.4.10

3、debug模式修改为x86(重要)

4、初始浏览器

#region 初始化浏览器
/// <summary>
/// 初始化浏览器
/// </summary>
private void InitBrowser()
{
    CefSettings settings = new CefSettings();

    settings.CefCommandLineArgs.Add("--ignore-urlfetcher-cert-requests", "1");
    settings.CefCommandLineArgs.Add("--ignore-certificate-errors", "1");  //证书过期
    settings.CefCommandLineArgs.Add("disable-usb-keyboard-detect", "1");
    settings.CefCommandLineArgs.Add("enable-media-stream", "1");  //可以调视频
    settings.CefCommandLineArgs.Add("no-proxy-server", "1");
    settings.CefCommandLineArgs.Add("enable-speech-input", "1");  //语音输入
    settings.CefCommandLineArgs.Add("touch-events", "1");
    settings.CefCommandLineArgs.Add("unsafely-treat-insecure-origin-as-secure", "https://txtrtc.sstms.net");
    //settings.CefCommandLineArgs.Add("unsafely-treat-insecure-origin-as-secure", Common.Common.GetDomain(GlobalParams.UrlPath));
    CefSharpSettings.WcfEnabled = true;

    Cef.Initialize(settings);
    chromeBrowser = new ChromiumWebBrowser(url);
    chromeBrowser.LifeSpanHandler = new OpenPageSelf();
    chromeBrowser.FocusHandler = null;

    //与js交互
    ////=========旧方式
    //CefSharpSettings.LegacyJavascriptBindingEnabled = true;
    //BindingOptions bindingOptions = new BindingOptions();
    ////如果不加此句,那么绑定的方法不能以大写字母开头
    //bindingOptions.CamelCaseJavascriptNames = false;
    //chromeBrowser.JavascriptObjectRepository.Register("YHFrame", frameCall, isAsync: false, options: bindingOptions);
    //=========旧方式END===

    //====新方式
    //chromeBrowser.JavascriptObjectRepository.ResolveObject += (sender, e) =>
    //{
    //    var repo = e.ObjectRepository;
    //    if (e.ObjectName == "YHFrame")
    //    {
    //        tempCommand = null;
    //        BindingOptions bindingOptions = null; //Binding options is an optional param, defaults to null
    //        bindingOptions = BindingOptions.DefaultBinder; //Use the default binder to serialize values into complex objects
    //        //bindingOptions = new BindingOptions { Binder = new MyCustomBinder() }); //Specify a custom binder
    //        repo.NameConverter = null; //No CamelCase of Javascript Names
    //                                   //For backwards compatability reasons the default NameConverter doesn't change the case of the objects returned from methods calls.
    //                                   //https://github.com/cefsharp/CefSharp/issues/2442
    //                                   //Use the new name converter to bound object method names and property names of returned objects converted to camelCase
    //                                   //repo.NameConverter = new CamelCaseJavascriptNameConverter();
    //        repo.Register("YHFrame", frameCall, isAsync: false, options: BindingOptions.DefaultBinder);
    //    }
    //};
    //=====新方式END===
    this.Controls.Add(chromeBrowser);
    chromeBrowser.Dock = DockStyle.Fill;
    chromeBrowser.KeyboardHandler = new CEFKeyBoardHander();
    chromeBrowser.RequestHandler = new ExampleRequestHandler();
    chromeBrowser.MenuHandler = new MenuHandler();
}

#endregion

5、其它设置

    #region 调试
    public class CEFKeyBoardHander : IKeyboardHandler
    {
        public bool OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey)
        {
            if (type == KeyType.KeyUp && Enum.IsDefined(typeof(Keys), windowsKeyCode))
            {
                var key = (Keys)windowsKeyCode;
                switch (key)
                {
                    case Keys.F12:
                        browser.ShowDevTools();
                        break;
                    case Keys.F5:

                        if (modifiers == CefEventFlags.ControlDown)
                        {
                            //MessageBox.Show("ctrl+f5");
                            browser.Reload(true); //强制忽略缓存

                        }
                        else
                        {
                            //MessageBox.Show("f5");
                            browser.Reload();
                        }
                        break;


                }
            }
            return false;
        }

        public bool OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut)
        {
            return false;
        }
    }
    #endregion

    #region 当前窗口打开
    internal class OpenPageSelf : ILifeSpanHandler
    {
        public bool DoClose(IWebBrowser browserControl, IBrowser browser)
        {
            return false;
        }

        public void OnAfterCreated(IWebBrowser browserControl, IBrowser browser)
        {

        }

        public void OnBeforeClose(IWebBrowser browserControl, IBrowser browser)
        {

        }

        public bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl,
string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures,
IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
        {
            string newWinOpen = Common.Common.GetQueryString("newWinOpen", targetUrl);
            var chromiumWebBrowser = (ChromiumWebBrowser)browserControl;

            if (newWinOpen == "1")
            {
                newBrowser = new ChromiumWebBrowser(); // chromiumWebBrowser;
                return false;
            }
            newBrowser = null;
            //var chromiumWebBrowser = (ChromiumWebBrowser)browserControl;
            chromiumWebBrowser.Load(targetUrl);
            return true; //Return true to cancel the popup creation copyright by codebye.com.
        }
    }
    #endregion

    #region 证书异常
    /// <summary>
    /// 证书异常
    /// </summary>
    public class ExampleRequestHandler : RequestHandler
    {
        protected override bool OnCertificateError(IWebBrowser chromiumWebBrowser, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback)
        {
            Task.Run(() =>
            {
                if (!callback.IsDisposed)
                {
                    using (callback)
                    {
                        //地址包含报表成分 跳过ssl验证
                        if (requestUrl.Contains("reportSystem"))
                        {
                            callback.Continue(true);//重点部分
                        }
                        else
                        {
                            callback.Continue(false);
                        }
                    }
                }
            });
            return true;
        }
    }
    #endregion

    #region 禁右键
    /// <summary>
    /// 禁右键
    /// </summary>
    internal class MenuHandler : IContextMenuHandler
    {
        public bool OnBeforeContextMenu(IWebBrowser browser, IBrowser ibrower, IFrame iframe, IContextMenuParams icontextmenuparams, IMenuModel imenumodel)
        {
            return false;
        }

        public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
        {
            return false;
            //throw new NotImplementedException();
        }

        public void OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame)
        {
            // throw new NotImplementedException();
        }

        public bool RunContextMenu(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback)
        {
            //throw new NotImplementedException();
            return false;
        }

        void IContextMenuHandler.OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
        {
            model.Clear();
        }
    }
    #endregion
View Code

 

posted @ 2024-08-26 09:41  ziff123  阅读(193)  评论(0编辑  收藏  举报