WebView2应用案例介绍

看了下,挺多文章介绍WebView2的,所以觉得看其他的文章就好了,本文章主要介绍一些日常自己在开发的案例,看这个文章,要有一些js、html的基础,还有用了DevExpress的包,所以MVVM实现会简单点。

1.嵌入本地HTML文件进行开发项目,通讯:WPF发送到HTML,HTML发送到WPF后台

1.1 页面

1.2 xaml代码,MainWindowView.xaml

<Window
    x:Class="YiFan.Host.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:local="clr-namespace:YiFan.Host"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:webView2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
    Title="MainWindow"
    Width="800"
    Height="450"
    Loaded="{DXEvent 'Loaded(@e(chrome))'}"
    mc:Ignorable="d">
    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="接受HTML消息:" />
            <TextBlock
                MinWidth="120"
                Margin="5,0"
                Text="{Binding Msg, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" />
            <TextBlock Margin="5,0" Text="发送到HTML消息:" />
            <TextBox
                Name="textTb"
                MinWidth="100"
                Margin="5,0" />
            <Button Click="{DXEvent 'SendToHTML(@e(textTb).Text)'}" Content="发送" />

        </StackPanel>
        <webView2:WebView2 Name="chrome" Grid.Row="1" />
    </Grid>
</Window>

1.3 WPF后台代码MainWindowViewModel.cs

using DevExpress.Mvvm;
using System;
using System.IO;
using Microsoft.Web.WebView2.Wpf;
using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;

namespace YiFan.Host
{
    public class MainWindowViewModel : ViewModelBase
    {
        private WebView2 webChrome = null;
        private string msg;
        public string Msg
        {
            get
            {
                return msg;
            }
            set
            {
                msg = value;
                RaisePropertyChanged(nameof(Msg));
            }
        }
        public void Loaded(WebView2 web)
        {
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "home.html");
            this.webChrome = web;
            this.webChrome.Source = new Uri(filePath);
            this.webChrome.CoreWebView2InitializationCompleted += WebChrome_CoreWebView2InitializationCompleted;
        }

        private void WebChrome_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
        {
            ((WebView2)sender).CoreWebView2.Settings.IsScriptEnabled = true;
            ((WebView2)sender).CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived;
        }

        private void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
        {
            //接收json转对象
            //string json = e.TryGetWebMessageAsString();
            //var person = JsonConvert.DeserializeObject<PersonInfo>(json);
            //Msg = $"姓名:{person.name},年龄:{person.age}";
            Msg = e.TryGetWebMessageAsString();
        }

        public void SendToHTML(string text)
        {
            this.webChrome.ExecuteScriptAsync($"getToWPF('{text}')");
        }
    }
    public class PersonInfo
    {
        public string name { get; set; }
        public int age { get; set; }
    }
}

1.4 html代码,home.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        <span>接受WPF的消息:</span>
        <span class="msgSpan"></span>
    </div>
    <div>
        <input type="text" class="msgInput">
        <button onclick="sendToWPF()">发送</button>
    </div>
    <script>
        function PersonInfo(name,age) {
            this.name = name
            this.age=age
        }
        const msgInput = document.querySelector('input.msgInput')
        const msgSpan = document.querySelector('span.msgSpan')
        function sendToWPF() {
            try {
                //发送对象转json
                //chrome.webview.postMessage(JSON.stringify(new PersonInfo('小明', 20)))
                chrome.webview.postMessage(msgInput.value)
            } catch (error) {
                alert(error.message)
            }
        }
        function getToWPF(text) {
            msgSpan.innerHTML = text
        }
    </script>
</body>

</html>

2. 操作js,通过百度案例进行,输入文字后搜索

 2.1 xaml代码,MainWindow.xaml

<Window
    x:Class="YiFan.Host.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:local="clr-namespace:YiFan.Host"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:webView2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
    Title="MainWindow"
    Width="800"
    Height="450"
    Loaded="{DXEvent 'Loaded(@e(chrome))'}"
    mc:Ignorable="d">
    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
    <Grid>
        <webView2:WebView2 Name="chrome" Grid.Row="1" />
    </Grid>
</Window>

 2.2 WPF后台代码MainWindowViewModel.cs

using DevExpress.Mvvm;
using System;
using System.IO;
using Microsoft.Web.WebView2.Wpf;
using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;

namespace YiFan.Host
{
    public class MainWindowViewModel : ViewModelBase
    {
        private WebView2 webChrome = null;
        private string msg;
        public string Msg
        {
            get
            {
                return msg;
            }
            set
            {
                msg = value;
                RaisePropertyChanged(nameof(Msg));
            }
        }
        public void Loaded(WebView2 web)
        {
            this.webChrome = web;
            this.webChrome.Source = new Uri(@"https://www.baidu.com");
            this.webChrome.NavigationCompleted += WebChrome_NavigationCompleted;
        }
        /// <summary>
        /// 导航完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WebChrome_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            if (!e.IsSuccess) return;
            //搜索框输入淘宝
            ((WebView2)sender).ExecuteScriptAsync("const kwInput=document.querySelector('input#kw.s_ipt'); kwInput&&(kwInput.value='淘宝')");
            //点击百度以下
            ((WebView2)sender).ExecuteScriptAsync("const queryBtn=document.querySelector('input#su'); queryBtn&&queryBtn.click()");
        }
    }
}

3.爬cookie信息,示例抖音达人号登录

 3.1 xaml代码,MainWindow.xaml

<Window
    x:Class="YiFan.Host.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:local="clr-namespace:YiFan.Host"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:webView2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
    Title="MainWindow"
    Width="800"
    Height="450"
    mc:Ignorable="d">
    <Grid>
        <webView2:WebView2 Name="webView" Grid.Row="1" />
    </Grid>
</Window>

3.2 WPF后台代码MainWindowViewModel.cs

using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace YiFan.Host
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.webView.Source = new Uri("https://buyin.jinritemai.com/mpa/account/login");
            this.webView.CoreWebView2InitializationCompleted += this.WebView_CoreWebView2InitializationCompleted;
        }
        public MasterLogonResult Result { get; set; }
        private void WebView_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
        {
            this.webView.CoreWebView2.WebResourceResponseReceived += CoreWebView2_WebResourceResponseReceived;
        }
        private void CoreWebView2_WebResourceResponseReceived(object sender, CoreWebView2WebResourceResponseReceivedEventArgs e)
        {
            //检索到buyin.jinritemai.com/index/getUser请求回来后,表示需要Cookie存储到webview2上了
            
            if (e.Request.Uri.Contains("buyin.jinritemai.com/index/getUser"))
            {
                var rep = e.Response.GetContentAsync().ContinueWith(async t =>
                {
                    if (t.Status == TaskStatus.RanToCompletion)
                    {
                        byte[] bytes = null;
                        using (var mem = new MemoryStream())
                        {
                            t.Result.CopyTo(mem);
                            bytes = mem.ToArray();
                        }
                        _ = Dispatcher.InvokeAsync(async () =>
                        {
                            var data = Encoding.UTF8.GetString(bytes);
                            var json = JsonConvert.DeserializeObject<MasterResponseBase<LoginMasterInfo>>(data);
                            //获取浏览器属于https://buyin.jinritemai.com/index/getUser的Cookie
                            List<CoreWebView2Cookie> list = await webView.CoreWebView2.CookieManager.GetCookiesAsync("https://buyin.jinritemai.com/index/getUser");
                            Result = new MasterLogonResult()
                            {
                                Cookie = string.Join(";", list.Select(c => c.Name + "=" + c.Value)),
                                UserName = json.data.user_name
                            };
                            //使用完成了,需要释放webview
                            //this.webView.Dispose();
                            //Close();
                        });
                    }
                });
            }
        }
    }
    public class MasterResponseBase<T>
    {
        public int st { get; set; }
        public int code { get; set; }
        public string msg { get; set; }
        public string log_id { get; set; }
        public T data { get; set; }
        public int total { get; set; }
    }
    public class LoginMasterInfo
    {
        public string user_name { get; set; }
        public string user_id { get; set; }
    }
    public class MasterLogonResult
    {
        public string UserName { get; set; }
        public string Cookie { get; set; }
    }
}

  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值