C#uses CefSharp embedded web pages-and gives an example of the interaction between C#and JS

C#uses CefSharp embedded web pages-and gives an example of the interaction between C#and JS

Is there a need to embed web pages in the client? CefSharp might be a good choice!

最后更新 3/27/2023 10:43 PM
沙漠尽头的狼
预计阅读 9 分钟
分类
.NET
标签
.NET C# CefSharp

Hello everyone, I am a wolf at the end of the desert.

This article introduces how to use CefSharp to embed a web page in C#WPF, and gives a simple example to demonstrate the interactive implementation of C#and web page (JS).

1. Example building steps

先给出本文示例代码:WpfWithCefSharpDemo

1. create a project

Create a WPF project, such as "WpfWithCefSharpDemo", similar to the Winform project.

2. create a page

嵌入的网页可以是在线的(即给出一个URL),也可以是一个离线的HTML网页,本文为了演示,在工程里直接创建网页test.html,属性设置生成操作内容复制到输出目录如果较新则复制

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>CefSharp测试</title>
    <script>
        // 测试在Web中调用C#的方法
        function callCSharpMethod() {
            window.cefSharpExample.testMethod("来自JS的调用");
        }

        // 测试C#调用JS的方法,只传递一个普通的字符串
        function displayMessage(message) {
            alert(message);
        }

        // 接收C#传递过来的JSON对象,并以表格形式展示在页面上
        function displayJson(json) {
            var obj = JSON.parse(json);
            var html = "<table border='1'>";
            for (var prop in obj) {
                html += "<tr>";
                html += "<td>" + prop + "</td>"
                html += "<td>" + obj[prop] + "</td>"
                html += "</tr>"
            }
            html += "</table>";
            document.getElementById("jsonTable").innerHTML = html;
        }
    
    </script>
</head>
<body>
<h1>CefSharp测试</h1>
<button onclick="callCSharpMethod()">调用C#方法</button>
<div id="jsonTable"></div>
</body>
</html>

The above code gives relevant comments, which should be clear:

  • JS方法callCSharpMethod:用于测试JS调用C#的方法,其中cefSharpExample为C#注册的一个对象,testMethod是其一个方法,JS中方法名首字母是小写(C#里按规则是大写),首字母这里有区别,要注意一下;
  • JS方法displayMessagedisplayJson:用于测试C#调用JS的方法,方法定义类似,前者入参是一个普通字符串,后者入参是一个JSON字符串。
  • The div element jsonTable is used to display the JSon object data sent from C#.

3. Add CefSharp package

To install the CefSharp package, you can search for CefSharp. Wpf in Visual Studio's NuGet Package Manager and install it.

4. Add CefSharp controls

MainWindow.xaml中引入CefSharp.Wpf命名空间(取别名为wpf,这里随意),将它的chromium控件加入到窗体中,顺带加几个测试按钮等:

<Window x:Class="WpfWithCefSharpDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:wpf="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"
        mc:Ignorable="d"
        Title="WPF加载CefSharp测试" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="35"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="50"></RowDefinition>
        </Grid.RowDefinitions>
        <TextBlock Text="下面显示的是网页内容"></TextBlock>
        <Border Grid.Row="1" BorderBrush="DarkOrange" BorderThickness="2">
            <wpf:ChromiumWebBrowser x:Name="Browser" Loaded="Browser_OnLoaded">
            </wpf:ChromiumWebBrowser>

        </Border>
        <Border Margin="3 5" Grid.Row="2" BorderBrush="Blue" BorderThickness="2" VerticalAlignment="Center">
            <StackPanel Orientation="Horizontal" Height="35">
                <TextBlock Text="右侧按钮是WPF按钮" VerticalAlignment="Center" Margin="5 3"></TextBlock>
                <Button Content="调用JS方法" Click="CallJSFunc_Click" Height="30" Padding="10 2"></Button>
                <Button Content="C#传递Json对象到网页" Click="SendJsonToWeb_Click" Height="30" Padding="10 2"></Button>
            </StackPanel>
        </Border>
    </Grid>
</Window>

5. Calling JS methods in C#

MainWindow.xaml.cs里,添加相关控件的事件处理方法,即C#调用JS方法的相关代码:

using CefSharp;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Text;
using System.Windows;

namespace WpfWithCefSharpDemo
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            // 允许以同步的方式注册C#的对象到JS中
            Browser.JavaScriptObjectRepository.Settings.LegacyBindingEnabled = true;
            CefSharpSettings.WcfEnabled = true;

            // 注册C#的对象到JS中的代码必须在Cef的Browser加载之前调用
            Browser.JavaScriptObjectRepository.Register("cefSharpExample", new CefSharpExample(), false,
                options: BindingOptions.DefaultBinder);
        }

        /// <summary>
        /// Cef浏览器控件加载完成后,加载网页内容,可以加载网页的Url,也可以加载网页内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Browser_OnLoaded(object sender, RoutedEventArgs e)
        {
            var htmlFile = $"{AppDomain.CurrentDomain.BaseDirectory}test.html";
            if (!File.Exists(htmlFile))
            {
                return;
            }

            var htmlContent = File.ReadAllText(htmlFile, Encoding.UTF8);
            Browser.LoadHtml(htmlContent);
        }

        /// <summary>
        /// C#里调用JS的一般方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CallJSFunc_Click(object sender, RoutedEventArgs e)
        {
            var jsCode = $"displayMessage('C#里的调用')";
            Browser.ExecuteScriptAsync(jsCode);
        }

        /// <summary>
        /// C#调用一个JS的方法,并传递一个JSON对象
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SendJsonToWeb_Click(object sender, RoutedEventArgs e)
        {
            var jsonContent = new
            {
                Id = 1,
                Name = "沙漠尽头的狼",
                Age = 25,
                WebSite="https://dotnet9.com"
            };
            var jsonStr = JsonConvert.SerializeObject(jsonContent);

            // 传递Json对象,即传递一个JSON字符串,和前面的一个示例一样
            var jsCode = $"displayJson('{jsonStr}')";
            Browser.ExecuteScriptAsync(jsCode);
        }
    }

    public class CefSharpExample
    {
        public void TestMethod(string message)
        {
            Application.Current.Dispatcher.Invoke(() => { MessageBox.Show("JS里的调用"); });
        }
    }
}

CefSharpExample用于封装JS调用的类及方法定义,注意C#这里TestMethod方法名首字母是大写的,前面创建的HTML网页调用的该方法名首字母小写,再提醒一次,这里的区别要注意。

6. effect display

JS调用C#的方法:黄色方框内显示的网页内容,点击HTML按钮调用C#方法测试。

C#调用JS的普通方法:蓝色方框内显示的WPF控件,点击WPF按钮调用JS方法测试。

C#传递Json对象给JS的方法:蓝色方框内,点击WPF按钮C#传递Json对象到网页测试。

2. Summary

Please complete the above example. If you have ever used WPF or Winform native WebBrowser controls, let's compare the advantages and disadvantages of WPF's own WebBrowser control and CefSharp to end this article (from ChatGPT answers). Welcome to leave a message and discuss:

    • Advantages of WPF's own WebBrowser control: **
  1. The WebBrowser control comes with WPF and does not require any other libraries or components to be installed.

  2. The WebBrowser control is based on the Internet Explorer kernel, so it has natural compatibility and stability in the Windows operating system.

  3. The WebBrowser control provides many browser-related events, such as Navigating, Navigated, LoadCompleted, etc. Through these events, we can control and provide feedback on web page loading and navigation.

    • Disadvantages of the WebBrowser control included in WPF: **
  1. The WebBrowser control uses an older version of the IE kernel, does not support modern HTML5, CSS3 and other standards, and its performance is not as good as CefSharp.

  2. The WebBrowser control has relatively few APIs, making it difficult to implement some advanced functions, such as blocking web navigation, custom rendering, etc.

    • CefSharp Advantages: **
  1. CefSharp is built on the Chromium project, supports the latest HTML5, CSS3 and other web standards, and performs better.

  2. CefSharp provides a rich set of APIs that allow us to implement a variety of advanced functions, such as customizing network requests, intercepting web navigation, modifying HTML content, etc.

  3. CefSharp uses a multi-threaded model and hardware-accelerated rendering, which does not block UI threads and provides better stability and security.

    • CefSharp Disadvantages: **
  1. CefSharp requires additional libraries or components to be installed, increasing the complexity of development.

  2. CefSharp may experience performance issues in some situations, such as when rendering on high-density screens.

Therefore, when selecting a Web browser control, we need to choose it based on specific needs. If you just simply display web content and don't require too many advanced functions, then WPF's own WebBrowser control is enough to meet your needs. But if you need to implement some complex functions, such as customizing network requests, blocking web navigation, etc., then CefSharp may be more suitable. In general, CefSharp has more powerful functions and higher performance than the WebBrowser control that comes with WPF, but it is also relatively more complex to use.

Reference:

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 4/25/2023

CefSharp custom cache implementation

Using CefSharp's caching function well can improve application performance and user experience, reduce network traffic and server load, and support offline access, which is a very useful feature.

继续阅读
同分类 / 同标签 4/22/2026

Support for. NET by operating system versions (250707 update)

Use virtual machines and test machines to test the support of each version of the operating system for. NET. After installing the operating system, it is passed by measuring the corresponding running time of the installation and being able to run the Stardust Agent.

继续阅读