Browse Source

单例wb2

qianyi
shanji 3 years ago
parent
commit
45209965fc
  1. 10
      BBWY.Client/App.xaml.cs
  2. 1
      BBWY.Client/GlobalContext.cs
  3. 95
      BBWY.Client/Views/Order/GrabJDMibole.xaml.cs
  4. 71
      BBWY.Client/WebView2Manager.cs

10
BBWY.Client/App.xaml.cs

@ -74,6 +74,16 @@ namespace BBWY.Client
base.OnStartup(e); base.OnStartup(e);
} }
protected override void OnExit(ExitEventArgs e)
{
using (var s = ServiceProvider.CreateScope())
{
var wb2m = s.ServiceProvider.GetRequiredService<WebView2Manager>();
wb2m.Close();
}
base.OnExit(e);
}
private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{ {
Console.WriteLine(e.Exception); Console.WriteLine(e.Exception);

1
BBWY.Client/GlobalContext.cs

@ -30,6 +30,5 @@ namespace BBWY.Client
public string _1688ApiHost { get; set; } public string _1688ApiHost { get; set; }
#endregion #endregion
} }
} }

95
BBWY.Client/Views/Order/GrabJDMibole.xaml.cs

@ -1,18 +1,9 @@
using Microsoft.Web.WebView2.Core; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf; using Microsoft.Web.WebView2.Wpf;
using System; using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection; using System.Reflection;
using System.Text;
using System.Windows; using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using io = System.IO; using io = System.IO;
namespace BBWY.Client.Views.Order namespace BBWY.Client.Views.Order
@ -22,7 +13,7 @@ namespace BBWY.Client.Views.Order
/// </summary> /// </summary>
public partial class GrabJDMibole : Window public partial class GrabJDMibole : Window
{ {
private WebView2 wb2; private WebView2Manager w2m;
//private Stopwatch sw; //private Stopwatch sw;
private string orderId; private string orderId;
@ -36,63 +27,47 @@ namespace BBWY.Client.Views.Order
private void GrabJDMibole_Unloaded(object sender, RoutedEventArgs e) private void GrabJDMibole_Unloaded(object sender, RoutedEventArgs e)
{ {
this.Unloaded -= GrabJDMibole_Unloaded; grid.Children.Remove(w2m.wb2);
if (wb2 != null && wb2.CoreWebView2 != null) w2m = null;
{
wb2.CoreWebView2InitializationCompleted -= Wb2_CoreWebView2InitializationCompleted;
wb2.NavigationCompleted -= Wb2_NavigationCompleted;
wb2.WebMessageReceived -= CoreWebView2_WebMessageReceived;
//wb2.Dispose();
Console.WriteLine("wb2 Disposed");
}
} }
private void GrabJDMibole_Loaded(object sender, RoutedEventArgs e) private void GrabJDMibole_Loaded(object sender, RoutedEventArgs e)
{ {
//sw = new Stopwatch(); var sp = (App.Current as App).ServiceProvider;
wb2 = new WebView2(); using (var s = sp.CreateScope())
grid.Children.Add(wb2);
//sw.Start();
var wb2Setting = CoreWebView2Environment.CreateAsync(userDataFolder: io.Path.Combine(io.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "WebView2UserData")).Result;
wb2.EnsureCoreWebView2Async(wb2Setting);
wb2.CoreWebView2InitializationCompleted += Wb2_CoreWebView2InitializationCompleted;
wb2.NavigationCompleted += Wb2_NavigationCompleted;
wb2.WebMessageReceived += CoreWebView2_WebMessageReceived;
}
private void Wb2_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
{
//sw.Stop();
//Console.WriteLine(sw.ElapsedMilliseconds);
wb2.CoreWebView2.Navigate($"https://neworder.shop.jd.com/order/orderDetail?orderId={orderId}");
}
private async void Wb2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
{
//Console.WriteLine(wb2.CoreWebView2.Source);
//Console.WriteLine(wb2.Source);
if (wb2.CoreWebView2.Source.StartsWith("https://passport.shop.jd.com/login"))
{ {
//首次打开需要登录 w2m = s.ServiceProvider.GetRequiredService<WebView2Manager>();
await wb2.CoreWebView2.ExecuteScriptAsync("window.scrollTo(790,150)");
await wb2.CoreWebView2.ExecuteScriptAsync("document.querySelector(\"div[data-tab-id='form']\").click()");
} }
else if (wb2.CoreWebView2.Source.StartsWith("https://neworder.shop.jd.com/order/orderDetail")) grid.Children.Add(w2m.wb2);
w2m.CoreWebView2InitializationCompleted = (e) =>
{
w2m.wb2.CoreWebView2.Navigate($"https://neworder.shop.jd.com/order/orderDetail?orderId={orderId}");
};
w2m.OnNavigationCompleted = async (e) =>
{ {
//进入订单详情页面,触发点击查看手机号 if (w2m.wb2.CoreWebView2.Source.StartsWith("https://passport.shop.jd.com/login"))
Console.WriteLine("触发查看手机号"); {
var js = @"var mobileNode = document.getElementById('mobile'); //首次打开需要登录
await w2m.wb2.CoreWebView2.ExecuteScriptAsync("window.scrollTo(790,150)");
await w2m.wb2.CoreWebView2.ExecuteScriptAsync("document.querySelector(\"div[data-tab-id='form']\").click()");
}
else if (w2m.wb2.CoreWebView2.Source.StartsWith("https://neworder.shop.jd.com/order/orderDetail"))
{
//进入订单详情页面,触发点击查看手机号
var js = @"var mobileNode = document.getElementById('mobile');
mobileNode.addEventListener('DOMNodeInserted',function(e){ var m=mobileNode.innerText; window.chrome.webview.postMessage(m);}); mobileNode.addEventListener('DOMNodeInserted',function(e){ var m=mobileNode.innerText; window.chrome.webview.postMessage(m);});
document.getElementById('viewOrderMobile').click();"; document.getElementById('viewOrderMobile').click();";
_ = await wb2.CoreWebView2.ExecuteScriptAsync(js); _ = await w2m.wb2.CoreWebView2.ExecuteScriptAsync(js);
} }
} };
w2m.OnWebMessageReceived = (e) =>
private void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e) {
{ var mobole = e.TryGetWebMessageAsString();
var mobole = e.TryGetWebMessageAsString(); this.Tag = mobole;
this.Tag = mobole; this.DialogResult = true;
this.DialogResult = true; this.Close();
this.Close(); };
} }
} }
} }

71
BBWY.Client/WebView2Manager.cs

@ -0,0 +1,71 @@
using BBWY.Common.Models;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
using System;
using System.Reflection;
using io = System.IO;
namespace BBWY.Client
{
public class WebView2Manager : IDenpendency
{
public WebView2 wb2 { get; private set; }
private bool isInitializationCompleted;
public WebView2Manager()
{
wb2 = new WebView2();
var wb2Setting = CoreWebView2Environment.CreateAsync(userDataFolder: io.Path.Combine(io.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "WebView2UserData")).Result;
wb2.EnsureCoreWebView2Async(wb2Setting);
wb2.CoreWebView2InitializationCompleted += Wb2_CoreWebView2InitializationCompleted;
wb2.NavigationCompleted += Wb2_NavigationCompleted;
wb2.WebMessageReceived += Wb2_WebMessageReceived;
}
public Action<CoreWebView2WebMessageReceivedEventArgs> OnWebMessageReceived;
public Action<CoreWebView2NavigationCompletedEventArgs> OnNavigationCompleted;
public Action<CoreWebView2InitializationCompletedEventArgs> CoreWebView2InitializationCompleted;
public bool IsInitializationCompleted { get => isInitializationCompleted; }
private void Wb2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
{
OnWebMessageReceived?.Invoke(e);
}
private void Wb2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
{
OnNavigationCompleted?.Invoke(e);
}
private void Wb2_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
isInitializationCompleted = true;
CoreWebView2InitializationCompleted?.Invoke(e);
}
public void Close()
{
if (wb2 != null && wb2.CoreWebView2 != null)
{
wb2.CoreWebView2InitializationCompleted -= Wb2_CoreWebView2InitializationCompleted;
wb2.NavigationCompleted -= Wb2_NavigationCompleted;
wb2.WebMessageReceived -= Wb2_WebMessageReceived;
var udf = wb2.CoreWebView2.Environment.UserDataFolder;
var wb2ProcessId = wb2.CoreWebView2.BrowserProcessId;
wb2.Dispose();
int timeout = 10;
try
{
while (System.Diagnostics.Process.GetProcessById(Convert.ToInt32(wb2ProcessId)) != null && timeout < 2000)
{
System.Threading.Thread.Sleep(10);
timeout += 10;
}
}
catch { }
io.Directory.Delete(udf, true);
}
}
}
}
Loading…
Cancel
Save