added address bar and search button

This commit is contained in:
Jason Stephen 2022-12-01 17:01:06 -08:00
Родитель 7f2fb288ad
Коммит 28807ea79d
2 изменённых файлов: 28 добавлений и 1 удалений

Просмотреть файл

@ -22,6 +22,9 @@
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox Name="addressBar" Grid.Column="0"/>
<Button x:Name="myButton" Grid.Column="1" Click="myButton_Click">Go</Button>
<controls:WebView2 x:Name="MyWebView" Grid.Row="1" Grid.ColumnSpan="2"
Source="https://www.microsoft.com" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>

Просмотреть файл

@ -8,6 +8,7 @@ using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.IO;
@ -30,11 +31,34 @@ namespace WebView2WinAppSDKSample
public MainWindow()
{
this.InitializeComponent();
MyWebView.NavigationStarting += EnsureHttps;
}
private void EnsureHttps(WebView2 sender, CoreWebView2NavigationStartingEventArgs args)
{
String uri = args.Uri;
if (!uri.StartsWith("https://"))
{
MyWebView.ExecuteScriptAsync($"alert('{uri} is not safe, try an https link')");
args.Cancel = true;
}
else
{
addressBar.Text = uri;
}
}
private void myButton_Click(object sender, RoutedEventArgs e)
{
//myButton.Content = "Clicked";
try
{
Uri targetUri = new Uri(addressBar.Text);
MyWebView.Source = targetUri;
}
catch (FormatException ex)
{
// Incorrect address entered.
}
}
}
}