使用 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 內核 的複合式應用程序!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章