MainWindow window using Blazor WebView2:
<Border Margin="0,0,0,0"
Background="Transparent"
BorderThickness="0"
CornerRadius="0,0,0,0">
<Grid>
<blazor:BlazorWebView x:Name="webView" HostPage="{Binding URL, Mode=OneWay}" Services="{DynamicResource services}" Margin="0,0,0,0" Width="0" Height="0">
<blazor:BlazorWebView.RootComponents>
<blazor:RootComponent Selector="#app" ComponentType="{x:Type local:Main}" />
</blazor:BlazorWebView.RootComponents>
</blazor:BlazorWebView>
<Image x:Name="LoaddingImage" Width="680" Source="/loadding.png" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Grid>
</Border>
The author has added a logo image here. This is because the WebView takes some time to load the page/address. On machines with poor performance, it may lead to a white screen for a period of time; therefore, adding a logo or loading image makes it more user-friendly.
After starting the MainWindow, check if WebView2 is installed on the system. If not installed, redirect to the download address or official website.
try
{
var version = CoreWebView2Environment.GetAvailableBrowserVersionString();
}
catch (Exception ex)
{
try
{
Process.Start(new ProcessStartInfo
{
FileName = "https://www.whuanle.cn",
UseShellExecute = true
});
}
catch { }
}
var window = this;
var blazorWebView = window.BlazorWebView;
Then define the BlazorWebView initialization event. During initialization, customize the WebView data directory location, etc.
blazorWebView.BlazorWebViewInitializing += (s, e) =>
{
// Custom WebView data storage directory
e.UserDataFolder = "D://aaa";
blazorWebView.WebView.CoreWebView2InitializationCompleted += (s, e) =>
{
// Clear the WebView, i.e., browser cache, every time the program starts
blazorWebView.WebView.CoreWebView2.Profile.ClearBrowsingDataAsync(CoreWebView2BrowsingDataKinds.DiskCache);
// When opening an address in WebView, allow certain non https://0.0.0.0:443 addresses to open within the program, otherwise these addresses will open in the browser
blazorWebView.UrlLoading += (s, e) =>
{
foreach (var item in new string[]{})
{
if (e.Url.IsBaseOf(item) || e.Url.ToString().StartsWith(item.ToString()))
{
e.UrlLoadingStrategy = UrlLoadingStrategy.OpenInWebView;
break;
}
}
};
};
};
Finally, when the BlazorWebView has fully loaded, hide the logo and display the page.
// Configure blazor loading page event
private void WebViewLoadedHander()
{
var window = this;
window.Dispatcher.InvokeAsync(() =>
{
window.BlazorWebView.Width = double.NaN;
window.BlazorWebView.Height = double.NaN;
window.LoaddingImage.IsEnabled = false;
window.LoaddingImage.Visibility = Visibility.Hidden;
});
}
文章评论