前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >WPF开发-使用WebView2加载页面及页面交互

WPF开发-使用WebView2加载页面及页面交互

作者头像
码客说
发布2022-06-12 12:37:47
9.2K0
发布2022-06-12 12:37:47
举报
文章被收录于专栏:码客码客

WebView2

WebView2和CEF相比,在WPF中CEF相当于把渲染的界面生成图片再加载,而WebView2则没有这一步,性能有显著提升。

但是这种方式暂时没有找到支持Flash的方法。

这种方式可以支持Win7,XP尚未进行测试。

但是在安装的时候64位的Win7竟然无法安装32位的WebView2 运行时,所以建议64位的就安装64位的运行时。

官方教程 https://docs.microsoft.com/zh-cn/microsoft-edge/webview2/get-started/wpf

安装运行时

WebView2 实在诱人,最新的 Edge(Chromium) 性能强悍,而且所有使用 WebView2 的应用可以共用一个运行时(说人话就是一个安装了应用时,其他应用就不用装了)。

Windows 11 已经自带 WebView2 ,就连 Office 也会自动部署 WebView2 ,目前 WebView2 已经被部署到 2亿台电脑,并且还在继续增加 …… 未来是属于 WebView2 的。

重要的是 WebView2 仍然支持老旧的、即将被淘汰的 Windows 7 —— 拥有良好的兼容性。

WebView2是依赖于Edge chromium内核的,有如下三种方式可以获取:

  1. 安装开发版的Edge (Chromium),稳定版的Edge目前不支持WebView控件,不知道后续会不会开放。
  2. 安装独立的WebView2 Runtime,它可以独立下载和升级。
  3. 程序内嵌入Edge chromium内核

这三种方式运行效果基本一致,主要特点是:

  • 前两种方式和以前使用IE的浏览器控件非常类似,浏览器内核和程序是分离的,程序可以保持非常小的体积,浏览器内核可以单独升级。
  • 第一种方式目前还不支持Edge的稳定版,无法使用于生产环境
  • 第三种方式和以前的CEF比较类似,将chromium嵌入了程序,可以控制chromium的版本,减少依赖性,同时可以控制浏览器的版本,避免升级导致的不稳定。 但是相应的程序包会特别大,配置也相对更麻烦。

所以这里我推荐第二种方式。

下载地址:

https://developer.microsoft.com/zh-cn/microsoft-edge/webview2/#download-section

项目使用

安装WebView2

安装Microsoft.Web.WebView2程序包

代码语言:javascript
复制
Install-Package Microsoft.Web.WebView2

添加名字空间

代码语言:javascript
复制
xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"

添加控件

代码语言:javascript
复制
<wv2:WebView2 Name="webView" Source="https://www.psvmc.cn"/>

判断运行时是否安装

注意

建议专门一个页面进行检测,检测成功后再跳转到展示页面。

判断是否安装

代码语言:javascript
复制
public static bool IsInstallWebview2()
{
  string result = "";
  try
  {
    result = CoreWebView2Environment.GetAvailableBrowserVersionString();
  }
  catch (System.Exception)
  {
  }
  if (result == "" || result == null)
  {
    return false;
  }
  return true;
}

检测并安装

代码语言:javascript
复制
private async Task InstallRuntimeAsync()
{
  // 解决下载文件报错:请求被中止: 未能创建 SSL/TLS 安全通道
  ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
  var webClient = new WebClient();
  bool isDownload = false;
  string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
  string MicrosoftEdgeWebview2Setup = System.IO.Path.Combine(desktopPath, "MicrosoftEdgeWebview2Setup.exe");
  try
  {
    webClient.DownloadFileCompleted += (s, e) =>
    {
      if (e.Error != null)
      {
        MessageBox.Show("下载失败:" + e.Error.Message);
      }
      else if (e.Cancelled)
      {
        MessageBox.Show("下载取消");
      }
      else
      {
        isDownload = true;
      }
    };
    await webClient.DownloadFileTaskAsync("https://go.microsoft.com/fwlink/p/?LinkId=2124703", MicrosoftEdgeWebview2Setup);
  }
  catch (Exception)
  {
  }
  if (isDownload)
  {
    await Task.Delay(300);
    await Task.Run(
      () =>
      {
        Process.Start(MicrosoftEdgeWebview2Setup, " /install").WaitForExit();
      }
    );

    if (IsInstallWebview2())
    {
      if (
        Environment.OSVersion.Version.Major < 6 ||
        Environment.OSVersion.Version.Major == 6 &&
        Environment.OSVersion.Version.Minor <= 1
      )
      {
        //Restart application in Win7 or lower OS
        var location = System.Reflection.Assembly.GetExecutingAssembly().Location;
        location = location.Replace(".dll", ".exe");
        Process.Start(location);
      }
      else
      {
        System.Windows.Forms.Application.Restart();
      }
      Close();
    }
  }
}

调用

代码语言:javascript
复制
private async void Window_Loaded(object sender, RoutedEventArgs e)
{
  webView.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted;
  sendBtn.Click += SendBtn_ClickAsync;
  await webView.EnsureCoreWebView2Async();
  if (!IsInstallWebview2())
  {
    await InstallRuntimeAsync();
  }
}

其中

代码语言:javascript
复制
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

解决在Win7环境下载文件报错:

请求被中止: 未能创建 SSL/TLS 安全通道

重启应用

代码语言:javascript
复制
if (
  Environment.OSVersion.Version.Major < 6 ||
  Environment.OSVersion.Version.Major == 6 &&
  Environment.OSVersion.Version.Minor <= 1
)
{
  //Restart application in Win7 or lower OS
  var location = System.Reflection.Assembly.GetExecutingAssembly().Location;
  location = location.Replace(".dll", ".exe");
  Process.Start(location);
}
else
{
  System.Windows.Forms.Application.Restart();
}
Close();

加载本地文件

你可以读取HTML文件,然后读取NavigateToString

代码语言:javascript
复制
private void Window_Loaded(object sender, RoutedEventArgs e)
{
  webView.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted;
  webView.EnsureCoreWebView2Async();
}

private void WebView_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
{
  string rootPath = Environment.CurrentDirectory;
  string filepath = System.IO.Path.Combine(rootPath, "html", "index.html");
  Console.WriteLine(filepath);
  if (webView != null && webView.CoreWebView2 != null)
  {
    string text = System.IO.File.ReadAllText(filepath);
    webView.CoreWebView2.NavigateToString(text);
  }
}

或者

你也可以通过Navigate连接到本地文件:

代码语言:javascript
复制
string rootPath = Environment.CurrentDirectory;
string filepath = System.IO.Path.Combine(rootPath, "html", "index.html");
webView.Source = new Uri("file:///" + filepath);

互操作

C#向JS发消息

本机代码

代码语言:javascript
复制
if (webView != null && webView.CoreWebView2 != null)
{
  webView.CoreWebView2.PostWebMessageAsString(inputTB.Text);
}

JS代码

代码语言:javascript
复制
<script type="text/javascript">
  window.chrome.webview.addEventListener('message', arg => {
    document.querySelector(".outer").innerHTML = arg.data;
  });
</script>

或者发送JSON

代码语言:javascript
复制
if (webView != null && webView.CoreWebView2 != null)
{
  webView.CoreWebView2.PostWebMessageAsJson("{\"color\":\"blue\"}");
}

JS接收

代码语言:javascript
复制
<script type="text/javascript">
  window.chrome.webview.addEventListener('message', arg => {
    document.querySelector(".outer").innerHTML = arg.data.color;
  });
</script>

唯一的差别在于

接收的时候会自动转换为JSON对象。不过我还是建议传递字符串,转换的操作放在JS中处理。

C#调用JS代码

代码语言:javascript
复制
private async void SendBtn_ClickAsync(object sender, RoutedEventArgs e)
{
  if (webView != null && webView.CoreWebView2 != null)
  {
    await webView.CoreWebView2.ExecuteScriptAsync("alert('123')");
  }
}

或者调用JS方法

代码语言:javascript
复制
function showmsg(msg) {
  alert(msg);
}

本机代码

代码语言:javascript
复制
private async void SendBtn_ClickAsync(object sender, RoutedEventArgs e)
{
  if (webView != null && webView.CoreWebView2 != null)
  {
    await webView.CoreWebView2.ExecuteScriptAsync("showmsg('你好')");
  }
}

JS调用C#代码

定义数据交互的类

代码语言:javascript
复制
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class ScriptCallbackObject
{
  public string GetMessageInfo()
  {
    return "C#返回的信息";
  }

  public void ShowMessage(string arg)
  {
    Console.WriteLine(arg);
    MessageBox.Show("【网页调用C#】:" + arg);
  }
}

代码中注册事件

代码语言:javascript
复制
private void Window_Loaded(object sender, RoutedEventArgs e)
{
  webView.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted;
  webView.EnsureCoreWebView2Async();
}

private void WebView_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
{
  if (webView != null && webView.CoreWebView2 != null)
  {
    //注册csobj脚本c#互操作
    webView.CoreWebView2.AddHostObjectToScript("csobj", new ScriptCallbackObject());
    //注册全局变量csobj
    webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("var csobj = window.chrome.webview.hostObjects.csobj;");
    webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("var csobj_sync= window.chrome.webview.hostObjects.sync.csobj;");
    
    //加载页面
    string rootPath = Environment.CurrentDirectory;
    string filepath = System.IO.Path.Combine(rootPath, "html", "index.html");
    string text = System.IO.File.ReadAllText(filepath);
    webView.CoreWebView2.NavigateToString(text);
  }
}

HTML中

异步调用取值

代码语言:javascript
复制
<script type="text/javascript">
  function myfunc() {
    window.chrome.webview.hostObjects.csobj.GetMessageInfo()
      .then(
        msg => {
          document.querySelector(".mytext").innerText = msg;
        }
    )
  }
</script>

当然上面的代码也可以简写为

代码语言:javascript
复制
function myfunc() {
  csobj.GetMessageInfo()
    .then(
      msg => {
        document.querySelector(".mytext").innerText = msg;
      }
  )
}

这是因为我们已经在C#中创建了JS的对象

代码语言:javascript
复制
webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("var csobj = window.chrome.webview.hostObjects.csobj;");

同步调用取值

代码语言:javascript
复制
<script type="text/javascript">
  function myfunc() {
    var msg = window.chrome.webview.hostObjects.sync.csobj.GetMessageInfo();
    document.querySelector(".mytext").innerText = msg;
  }
</script>

同步调用

代码语言:javascript
复制
<script type="text/javascript">
  function myfunc() {
    window.chrome.webview.hostObjects.sync.csobj.ShowMessage("你好吗");
  }
</script>

注意

window.chrome.webview.hostObjects.csobj是异步的,要想同步就要用window.chrome.webview.hostObjects.sync.csobj

Flash支持

很遗憾,现在还没找到WebView2支持Flash的方式。

目前要想支持Flash只有两种选择:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-03-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • WebView2
  • 安装运行时
  • 项目使用
    • 安装WebView2
      • 判断运行时是否安装
        • 判断是否安装
        • 检测并安装
        • 重启应用
      • 加载本地文件
        • 互操作
          • C#向JS发消息
          • C#调用JS代码
          • JS调用C#代码
      • Flash支持
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档