1

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

 5 months ago
source link: https://www.cnblogs.com/sheng_chao/p/18009246
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

先看实现效果

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

1d43bed9-b5a8-4941-a2c6-56ef4e3152cf.png
15ea0fe9-0392-4acc-bc5a-12735d16d537.png

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

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>
8181e6db-9cde-4b6b-9843-c0e30f0e8d2b.png

2. 响应事件

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

  • NavigationStarting
  • SourceChanged
  • ContentLoading
  • HistoryChanged
  • NavigationCompleted
869f4392-9513-42ce-aa1d-40220f32008f.png

例:修改构造函数以匹配以下代码段并添加 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 内核 的复合式应用程序!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK