在上一篇博文《WinForm内置浏览器之CefSharp 笔记一》,简单介绍了CefSharp的快速入门。这篇博文接着上篇,主要记录C#如果调用JS中的方法。
本文主要参照Github示例:传送门
在这里插入图片描述

CefSharp学习笔记

加载自定义网页

  • 修改网址,使用ChromiumWebBrowser类的Load方法,直接直接输入网址,也可以加载本地的html文件。
 m_chromeBrowser.Load(“https://www.baidu.com”);
  • 加载自定义html,使用ChromiumWebBrowser类的LoadHtml方法。
m_chromeBrowser.LoadHtml("<html><body>Hello world</body></html>", "http://customrendering/");

JavaScript调用执行C#中的类

这块主要调用ChromiumWebBrowser类的RegisterJsObject方法,示例如下:(CefCustomObject(chromeBrowse是一个自定义类,可以在上一篇文章中找到)

chromeBrowser.RegisterJsObject("cefCustomObject", new CefCustomObject(chromeBrowser, this));

C#调用执行JavaScript脚本

这块主要调用ChromiumWebBrowser类的ExecuteScriptAsync方法,示例如下:

 private void buttonExecJavaScriptFromWinforms_Click(object sender, EventArgs e)
 {
     m_chromeBrowser.LoadHtml("<html><body>Hello world</body></html>", "http://customrendering/");
     var script = "document.body.style.backgroundColor = 'red';";
     m_chromeBrowser.ExecuteScriptAsync(script);
 }

还可以这样执行调用:

browser.GetMainFrame().ExecuteJavaScriptAsync(script);

这块可能会遇到这个问题Browser is not yet initialized. Use the IsBrowserInitializedChanged event and check the IsBrowserInitialized property to determine when the browser has been intialized.
官方建议调用方式:参考链接
这块我使用的ExecuteScriptAsyncWhenPageLoaded方法执行脚本来避免上面的问题。

C#调用JavaScript,并获取返回的结果

这块因为是异步执行的,所以要获取结果要参考下面这种方式

private void buttonReturnDataFromJavaScript_Click(object sender, EventArgs e)
{
     m_chromeBrowser.LoadHtml("<html><body>Hello world</body></html>", "http://customrendering/");

     StringBuilder sb = new StringBuilder();
     sb.AppendLine("function tempFunction() {");
     sb.AppendLine("     var w = window.innerWidth;");
     sb.AppendLine("     var h = window.innerHeight;");
     sb.AppendLine("");
     sb.AppendLine("     return w*h;");
     sb.AppendLine("}");
     sb.AppendLine("tempFunction();");

     var task = m_chromeBrowser.EvaluateScriptAsync(sb.ToString());

     task.ContinueWith(t =>
     {
         if (!t.IsFaulted)
         {
             var response = t.Result;

             if ( response.Success == true )
             {
                 MessageBox.Show( response.Result.ToString() );
             }
         }
     }, TaskScheduler.FromCurrentSynchronizationContext());
 }

屏蔽浏览器的右键菜单

新建MenuHandler类

    public class MenuHandler : CefSharp.IContextMenuHandler
    {

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

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

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

        bool CefSharp.IContextMenuHandler.RunContextMenu(CefSharp.IWebBrowser browserControl, CefSharp.IBrowser browser, CefSharp.IFrame frame, CefSharp.IContextMenuParams parameters, CefSharp.IMenuModel model, CefSharp.IRunContextMenuCallback callback)
        {
            return false;
        }
    }

设置ChromiumWebBrowser对象的MenuHandler属性,即可屏蔽右键菜单

m_chromeBrowser = new ChromiumWebBrowser(page);
//屏蔽右键菜单
m_chromeBrowser.MenuHandler = new MenuHandler();

推荐资源:

  1. CefSharp初识–把网页移到桌面(我觉得还不错,感兴趣的可以看一下)
  2. Frequently asked questions(常见问题)
Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐