CefSharp 与 JS交互

创建WPF项目,然后NuGet安装包:CefSharp.Wpf

一、基本使用

Loaded += (m, n) =>
{
    #region 加载HTML
    CefSharpSettings.WcfEnabled = true;
    var browser = CefSharpHelper.Browser;
    string address = ConfigurationManager.AppSettings["STARTURL"];
    Regex regex = new Regex(@"^https?:\/\/(?<host>[^/]+)(?<path>\/[^?]*)?(?<query>\?[^#]*)?(?<anchor>\#.*)?$");
    address = regex.IsMatch(address) ? ConfigurationManager.AppSettings["STARTURL"] : System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, address);
    //清理本地存储数据
    Cef.GetGlobalCookieManager().DeleteCookies("", "");
    browser.MenuHandler = new MenuHandler();
    //注册JsObj对象JS调用C#
    browser.JavascriptObjectRepository.Register("interop", new JavascriptCallback(browser, this), isAsync: false);
    browser.Load(address);
    gridMain.Children.Add(browser);
    #endregion
};

 

 二、阻止WebBrower默认行为

#region 阻止WebBrower默认行为
/// <summary>
/// 调用方式:
/// browser.MenuHandler = new MenuHandler();
/// </summary>
public class MenuHandler : IContextMenuHandler
{
    public void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
    {
        model.Clear();
    }
    public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
    {
        return false;
    }
    public void OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame)
    {
    }
    public bool RunContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback)
    {
        return false;
    }
}
#endregion

 

三、提供前端HTML调用函数

#region CefSharp帮助类
/// <summary>
/// 单列模式
/// </summary>
public class CefSharpHelper
{
private static ChromiumWebBrowser _browser;
private static readonly object _syncRoot = new object();

public static ChromiumWebBrowser Browser
{
    get
    {
        if (_browser == null)
        {
            lock (_syncRoot)
            {
                if (_browser == null)
                {
                    CefSettings settings = new CefSettings();
                    Cef.Initialize(settings);
                    // 创建浏览器实例
                    _browser = new ChromiumWebBrowser();
                }
            }
        }
        return _browser;
    }
}
}
/// <summary>
/// JS调用C#函数
/// </summary>
public class JavascriptCallback
{
private static MainWindow _window;
private static ChromiumWebBrowser _chromiumWebBrowser;
//构造方法
public JavascriptCallback(ChromiumWebBrowser chromiumWebBrowser, MainWindow window)
{
    _window = window;
    _chromiumWebBrowser = chromiumWebBrowser;
    _chromiumWebBrowser.FrameLoadEnd += OnFrameLoadEnd;
}
// 窗口加载完毕时需要执行的全局JS对象
public void OnFrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
    if (e.Frame.IsMain)
    {
        //显示源代码
        //_chromiumWebBrowser.ShowDevTools();
        _chromiumWebBrowser.GetFocusedFrame().EvaluateScriptAsync("(function(){CefSharp.BindObjectAsync('interop');})()").Await();
    }
}
// 提供前端HTML调用,如:interop.on(number);
public bool on(string input)
{
    int number;
    if (int.TryParse(input, out number))
    {
        return true;
    }
    return false;
}
// 提供前端HTML调用,如:interop.off(number);
public bool off(string input)
{
    int number;
    if (int.TryParse(input, out number))
    {
        return true;
    }
    return false;
}
}
#endregion

 

四、配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="STARTURL" value="index.html"/>
  </appSettings>  
</configuration>

 

posted @ 2023-12-11 11:56  microsoft-zhcn  阅读(83)  评论(0编辑  收藏  举报