使用 WPF + Chrome 内核实现高稳定性的在线客服系统复合应用程序

对于在线客服与营销系统,客服端指的是后台提供服务的客服或营销人员,他们使用客服程序在后台观察网站的被访情况,开展营销活动或提供客户服务。在本篇文章中,我将详细介绍如何通过 WPF + Chrome 内核的方式实现复合客服端应用程序。

先看实现效果

客服程序界面中的 聊天记录部分、文字输入框部分 使用的是基于 Chrome 内核的 WebView2 进行呈现的。

客服端

访客端

视频实拍:演示升讯威在线客服系统在网络中断,直接禁用网卡,拔掉网线的情况下,也不丢消息,不出异常。

https://blog.shengxunwei.com/Home/Post/fe432a51-337c-4558-b9e8-347b58cbcd53


要实现这样的效果只需三个步骤

  • 嵌入组件
  • 响应事件
  • 调用 JavaScript 函数

1. 嵌入组件

首先使用 NuGet 将 WebView2 SDK 添加到项目中,然后将 WebView 添加窗口界面。

<Window x:Class="WPF_Getting_Started.MainWindow"
        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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:{YOUR PROJECT NAME}"
        xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
        mc:Ignorable="d"
        Title="MainWindow"
        Height="450"
        Width="800"
>
    <Grid>
     <DockPanel>
     <wv2:WebView2 Name="webView"
                  Source="https://www.microsoft.com"
     />
    </DockPanel>
    </Grid>
</Window>

2. 响应事件

在网页导航期间,WebView2 控件将引发事件。 承载 WebView2 控件的应用侦听以下事件。

  • NavigationStarting
  • SourceChanged
  • ContentLoading
  • HistoryChanged
  • NavigationCompleted

例:修改构造函数以匹配以下代码段并添加 EnsureHttps 函数。


public MainWindow()
{
    InitializeComponent();
    webView.NavigationStarting += EnsureHttps;
}

void EnsureHttps(object sender, CoreWebView2NavigationStartingEventArgs args)
{
    String uri = args.Uri;
    if (!uri.StartsWith("https://"))
    {
        args.Cancel = true;
    }
}

3. 调用 JavaScript 函数

可以在运行时使用主机应用将 JavaScript 代码注入控件。 可以运行任意 JavaScript 或添加初始化脚本。 在删除 JavaScript 之前,注入的 JavaScript 适用于所有新的顶级文档和任何子框架。

例如,添加在用户导航到非 HTTPS 网站时发送警报的脚本。 修改 EnsureHttps 函数以将脚本注入到使用 ExecuteScriptAsync 方法的 Web 内容中。


void EnsureHttps(object sender, CoreWebView2NavigationStartingEventArgs args)
{
    String uri = args.Uri;
    if (!uri.StartsWith("https://"))
    {
        webView.CoreWebView2.ExecuteScriptAsync($"alert('{uri} is not safe, try an https link')");
        args.Cancel = true;
    }
}

完成

只需要以上简单三个步骤,嵌入组件、响应事件、调用 JavaScript 函数。就可以完成 WPF + Chrome 内核 的复合式应用程序!

posted @ 2024-02-06 10:13  升讯威在线客服系统  阅读(400)  评论(0编辑  收藏  举报